aboutsummaryrefslogtreecommitdiff
path: root/src/dht/gnunet-service-dht.c
blob: 48661fd888753bceb62ea6e7919f163416bb10b1 (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
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
/*
     This file is part of GNUnet.
     (C) 2009, 2010 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.
*/

/**
 * @file dht/gnunet-service-dht.c
 * @brief main DHT service shell, building block for DHT implementations
 * @author Christian Grothoff
 * @author Nathan Evans
 */

#include "platform.h"
#include "gnunet_client_lib.h"
#include "gnunet_getopt_lib.h"
#include "gnunet_os_lib.h"
#include "gnunet_protocols.h"
#include "gnunet_service_lib.h"
#include "gnunet_core_service.h"
#include "gnunet_signal_lib.h"
#include "gnunet_util_lib.h"
#include "gnunet_datacache_lib.h"
#include "gnunet_transport_service.h"
#include "gnunet_hello_lib.h"
#include "gnunet_dht_service.h"
#include "gnunet_statistics_service.h"
#include "dhtlog.h"
#include "dht.h"
#include <fenv.h>

#define PRINT_TABLES GNUNET_NO

#define REAL_DISTANCE GNUNET_NO

#define EXTRA_CHECKS GNUNET_NO

/**
 * How many buckets will we allow total.
 */
#define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8

/**
 * Should the DHT issue FIND_PEER requests to get better routing tables?
 */
#define DEFAULT_DO_FIND_PEER GNUNET_YES

/**
 * Defines whether find peer requests send their HELLO's outgoing,
 * or expect replies to contain hellos.
 */
#define FIND_PEER_WITH_HELLO GNUNET_YES

/**
 * What is the maximum number of peers in a given bucket.
 */
#define DEFAULT_BUCKET_SIZE 4

/**
 * Minimum number of peers we need for "good" routing,
 * any less than this and we will allow messages to
 * travel much further through the network!
 */
#define MINIMUM_PEER_THRESHOLD 20

#define DHT_MAX_RECENT 1000

#define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)

/**
 * Default time to wait to send messages on behalf of other peers.
 */
#define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)

/**
 * Default importance for handling messages on behalf of other peers.
 */
#define DHT_DEFAULT_P2P_IMPORTANCE 0

/**
 * How long to keep recent requests around by default.
 */
#define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)

/**
 * Default time to wait to send find peer messages sent by the dht service.
 */
#define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)

/**
 * Default importance for find peer messages sent by the dht service.
 */
#define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8

/**
 * Default replication parameter for find peer messages sent by the dht service.
 */
#define DHT_DEFAULT_PUT_REPLICATION 4

/**
 * Default replication parameter for find peer messages sent by the dht service.
 */
#define DHT_DEFAULT_FIND_PEER_REPLICATION 4

/**
 * Default options for find peer requests sent by the dht service.
 */
#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
/*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/

/**
 * How long at least to wait before sending another find peer request.
 */
#define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)

/**
 * How long at most to wait before sending another find peer request.
 */
#define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)

/**
 * How often to update our preference levels for peers in our routing tables.
 */
#define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)

/**
 * How long at most on average will we allow a reply forward to take
 * (before we quit sending out new requests)
 */
#define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)

/**
 * How many initial requests to send out (in true Kademlia fashion)
 */
#define DHT_KADEMLIA_REPLICATION 3

/*
 * Default frequency for sending malicious get messages
 */
#define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */

/*
 * Default frequency for sending malicious put messages
 */
#define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */

/**
 * Type for a malicious request, so we can ignore it during testing
 */
#define DHT_MALICIOUS_MESSAGE_TYPE 42

#define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)

/**
 * Real maximum number of hops, at which point we refuse
 * to forward the message.
 */
#define DEFAULT_MAX_HOPS 10

/**
 * How many time differences between requesting a core send and
 * the actual callback to remember.
 */
#define MAX_REPLY_TIMES 8

enum ConvergenceOptions
{
   /**
    * Use the linear method for convergence.
    */
   DHT_CONVERGE_LINEAR,

   /**
    * Converge using a fast converging square
    * function.
    */
   DHT_CONVERGE_SQUARE,

   /**
    * Converge using a slower exponential
    * function.
    */
   DHT_CONVERGE_EXPONENTIAL,

   /**
    * Don't do any special convergence, allow
    * the algorithm to hopefully route to closer
    * peers more often.
    */
   DHT_CONVERGE_RANDOM
};

/**
 * Linked list of messages to send to clients.
 */
struct P2PPendingMessage
{
  /**
   * Pointer to next item in the list
   */
  struct P2PPendingMessage *next;

  /**
   * Pointer to previous item in the list
   */
  struct P2PPendingMessage *prev;

  /**
   * Message importance level.
   */
  unsigned int importance;

  /**
   * Time when this request was scheduled to be sent.
   */
  struct GNUNET_TIME_Absolute scheduled;

  /**
   * How long to wait before sending message.
   */
  struct GNUNET_TIME_Relative timeout;

  /**
   * Actual message to be sent; // avoid allocation
   */
  const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);

};

/**
 * Per-peer information.
 */
struct PeerInfo
{
  /**
   * Next peer entry (DLL)
   */
  struct PeerInfo *next;

  /**
   *  Prev peer entry (DLL)
   */
  struct PeerInfo *prev;

  /**
   * Head of pending messages to be sent to this peer.
   */
  struct P2PPendingMessage *head;

  /**
   * Tail of pending messages to be sent to this peer.
   */
  struct P2PPendingMessage *tail;

  /**
   * Core handle for sending messages to this peer.
   */
  struct GNUNET_CORE_TransmitHandle *th;

  /**
   * Task for scheduling message sends.
   */
  GNUNET_SCHEDULER_TaskIdentifier send_task;

  /**
   * Task for scheduling preference updates
   */
  GNUNET_SCHEDULER_TaskIdentifier preference_task;

  /**
   * Preference update context
   */
  struct GNUNET_CORE_InformationRequestContext *info_ctx;

  /**
   * What is the average latency for replies received?
   */
  struct GNUNET_TIME_Relative latency;

  /**
   * What is the identity of the peer?
   */
  struct GNUNET_PeerIdentity id;

  /**
   * Transport level distance to peer.
   */
  unsigned int distance;

  /**
   * Holds matching bits from peer to current target,
   * used for distance comparisons between peers. May
   * be considered a really bad idea.
   * FIXME: remove this value (create struct which holds
   *        a single peerinfo and the matching bits, use
   *        that to pass to comparitor)
   */
  unsigned int matching_bits;

  /**
   * Task for scheduling periodic ping messages for this peer.
   */
  GNUNET_SCHEDULER_TaskIdentifier ping_task;
};

/**
 * Peers are grouped into buckets.
 */
struct PeerBucket
{
  /**
   * Head of DLL
   */
  struct PeerInfo *head;

  /**
   * Tail of DLL
   */
  struct PeerInfo *tail;

  /**
   * Number of peers in the bucket.
   */
  unsigned int peers_size;
};

/**
 * Linked list of messages to send to clients.
 */
struct PendingMessage
{
  /**
   * Pointer to next item in the list
   */
  struct PendingMessage *next;

  /**
   * Pointer to previous item in the list
   */
  struct PendingMessage *prev;

  /**
   * Actual message to be sent; // avoid allocation
   */
  const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);

};

/**
 * Struct containing information about a client,
 * handle to connect to it, and any pending messages
 * that need to be sent to it.
 */
struct ClientList
{
  /**
   * Linked list of active clients
   */
  struct ClientList *next;

  /**
   * The handle to this client
   */
  struct GNUNET_SERVER_Client *client_handle;

  /**
   * Handle to the current transmission request, NULL
   * if none pending.
   */
  struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;

  /**
   * Linked list of pending messages for this client
   */
  struct PendingMessage *pending_head;

  /**
   * Tail of linked list of pending messages for this client
   */
  struct PendingMessage *pending_tail;
};


/**
 * Context containing information about a DHT message received.
 */
struct DHT_MessageContext
{
  /**
   * The client this request was received from.
   * (NULL if received from another peer)
   */
  struct ClientList *client;

  /**
   * The peer this request was received from.
   * (NULL if received from local client)
   */
  const struct GNUNET_PeerIdentity *peer;

  /**
   * The key this request was about
   */
  GNUNET_HashCode key;

  /**
   * The unique identifier of this request
   */
  uint64_t unique_id;

  /**
   * Desired replication level
   */
  uint32_t replication;

  /**
   * Network size estimate, either ours or the sum of
   * those routed to thus far. =~ Log of number of peers
   * chosen from for this request.
   */
  uint32_t network_size;

  /**
   * Any message options for this request
   */
  uint32_t msg_options;

  /**
   * How many hops has the message already traversed?
   */
  uint32_t hop_count;

  /**
   * How important is this message?
   */
  unsigned int importance;

  /**
   * How long should we wait to transmit this request?
   */
  struct GNUNET_TIME_Relative timeout;

  /**
   * Bloomfilter for this routing request.
   */
  struct GNUNET_CONTAINER_BloomFilter *bloom;

  /**
   * Did we forward this message? (may need to remember it!)
   */
  int forwarded;

  /**
   * Are we the closest known peer to this key (out of our neighbors?)
   */
  int closest;
};

/**
 * Record used for remembering what peers are waiting for what
 * responses (based on search key).
 */
struct DHTRouteSource
{
  /**
   * This is a DLL.
   */
  struct DHTRouteSource *next;

  /**
   * This is a DLL.
   */
  struct DHTRouteSource *prev;

  /**
   * Source of the request.  Replies should be forwarded to
   * this peer.
   */
  struct GNUNET_PeerIdentity source;

  /**
   * If this was a local request, remember the client; otherwise NULL.
   */
  struct ClientList *client;

  /**
   * Pointer to this nodes heap location (for removal)
   */
  struct GNUNET_CONTAINER_HeapNode *hnode;

  /**
   * Back pointer to the record storing this information.
   */
  struct DHTQueryRecord *record;

  /**
   * Task to remove this entry on timeout.
   */
  GNUNET_SCHEDULER_TaskIdentifier delete_task;

  /**
   * Bloomfilter of peers we have already sent back as
   * replies to the initial request.  Allows us to not
   * forward the same peer multiple times for a find peer
   * request.
   */
  struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;

};

/**
 * Entry in the DHT routing table.
 */
struct DHTQueryRecord
{
  /**
   * Head of DLL for result forwarding.
   */
  struct DHTRouteSource *head;

  /**
   * Tail of DLL for result forwarding.
   */
  struct DHTRouteSource *tail;

  /**
   * Key that the record concerns.
   */
  GNUNET_HashCode key;

  /**
   * GET message of this record (what we already forwarded?).
   */
  //DV_DHT_MESSAGE get; Try to get away with not saving this.

  /**
   * Bloomfilter of the peers we've replied to so far
   */
  //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.

};

/**
 * Context used to calculate the number of find peer messages
 * per X time units since our last scheduled find peer message
 * was sent.  If we have seen too many messages, delay or don't
 * send our own out.
 */
struct FindPeerMessageContext
{
  unsigned int count;

  struct GNUNET_TIME_Absolute start;

  struct GNUNET_TIME_Absolute end;
};

/**
 * DHT Routing results structure
 */
struct DHTResults
{
  /*
   * Min heap for removal upon reaching limit
   */
  struct GNUNET_CONTAINER_Heap *minHeap;

  /*
   * Hashmap for fast key based lookup
   */
  struct GNUNET_CONTAINER_MultiHashMap *hashmap;

};

/**
 * DHT structure for recent requests.
 */
struct RecentRequests
{
  /*
   * Min heap for removal upon reaching limit
   */
  struct GNUNET_CONTAINER_Heap *minHeap;

  /*
   * Hashmap for key based lookup
   */
  struct GNUNET_CONTAINER_MultiHashMap *hashmap;
};

struct RecentRequest
{
  /**
   * Position of this node in the min heap.
   */
  struct GNUNET_CONTAINER_HeapNode *heap_node;

  /**
   * Bloomfilter containing entries for peers
   * we forwarded this request to.
   */
  struct GNUNET_CONTAINER_BloomFilter *bloom;

  /**
   * Timestamp of this request, for ordering
   * the min heap.
   */
  struct GNUNET_TIME_Absolute timestamp;

  /**
   * Key of this request.
   */
  GNUNET_HashCode key;

  /**
   * Unique identifier for this request.
   */
  uint64_t uid;

  /**
   * Task to remove this entry on timeout.
   */
  GNUNET_SCHEDULER_TaskIdentifier remove_task;
};

struct RepublishContext
{
  /**
   * Key to republish.
   */
  GNUNET_HashCode key;

  /**
   * Type of the data.
   */
  unsigned int type;

};

/**
 * Which kind of convergence will we be using?
 */
enum ConvergenceOptions converge_option;

/**
 * Modifier for the convergence function
 */
float converge_modifier;

/**
 * Recent requests by hash/uid and by time inserted.
 */
static struct RecentRequests recent;

/**
 * Context to use to calculate find peer rates.
 */
static struct FindPeerMessageContext find_peer_context;

/**
 * Don't use our routing algorithm, always route
 * to closest peer; initially send requests to 3
 * peers.
 */
static unsigned int strict_kademlia;

/**
 * Routing option to end routing when closest peer found.
 */
static unsigned int stop_on_closest;

/**
 * Routing option to end routing when data is found.
 */
static unsigned int stop_on_found;

/**
 * Whether DHT needs to manage find peer requests, or
 * an external force will do it on behalf of the DHT.
 */
static unsigned int do_find_peer;

/**
 * Once we have stored an item in the DHT, refresh it
 * according to our republish interval.
 */
static unsigned int do_republish;

/**
 * Use the "real" distance metric when selecting the
 * next routing hop.  Can be less accurate.
 */
static unsigned int use_real_distance;

/**
 * How many peers have we added since we sent out our last
 * find peer request?
 */
static unsigned int newly_found_peers;

/**
 * Container of active queries we should remember
 */
static struct DHTResults forward_list;

/**
 * Handle to the datacache service (for inserting/retrieving data)
 */
static struct GNUNET_DATACACHE_Handle *datacache;

/**
 * Handle for the statistics service.
 */
struct GNUNET_STATISTICS_Handle *stats;

/**
 * The main scheduler to use for the DHT service
 */
static struct GNUNET_SCHEDULER_Handle *sched;

/**
 * The configuration the DHT service is running with
 */
static const struct GNUNET_CONFIGURATION_Handle *cfg;

/**
 * Handle to the core service
 */
static struct GNUNET_CORE_Handle *coreAPI;

/**
 * Handle to the transport service, for getting our hello
 */
static struct GNUNET_TRANSPORT_Handle *transport_handle;

/**
 * The identity of our peer.
 */
static struct GNUNET_PeerIdentity my_identity;

/**
 * Short id of the peer, for printing
 */
static char *my_short_id;

/**
 * Our HELLO
 */
static struct GNUNET_MessageHeader *my_hello;

/**
 * Task to run when we shut down, cleaning up all our trash
 */
static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;

/**
 * The lowest currently used bucket.
 */
static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */

/**
 * The maximum number of hops before we stop routing messages.
 */
static unsigned long long max_hops;

/**
 * How often to republish content we have previously stored.
 */
static struct GNUNET_TIME_Relative dht_republish_frequency;

/**
 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
 */
static int use_max_hops;

/**
 * The buckets (Kademlia routing table, complete with growth).
 * Array of size MAX_BUCKET_SIZE.
 */
static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */

/**
 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
 */
static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;

/**
 * Recently seen find peer requests.
 */
static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;

/**
 * Maximum size for each bucket.
 */
static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */

/**
 * List of active clients.
 */
static struct ClientList *client_list;

/**
 * Handle to the DHT logger.
 */
static struct GNUNET_DHTLOG_Handle *dhtlog_handle;

/*
 * Whether or not to send routing debugging information
 * to the dht logging server
 */
static unsigned int debug_routes;

/*
 * Whether or not to send FULL route information to
 * logging server
 */
static unsigned int debug_routes_extended;

/*
 * GNUNET_YES or GNUNET_NO, whether or not to act as
 * a malicious node which drops all messages
 */
static unsigned int malicious_dropper;

/*
 * GNUNET_YES or GNUNET_NO, whether or not to act as
 * a malicious node which sends out lots of GETS
 */
static unsigned int malicious_getter;

/**
 * GNUNET_YES or GNUNET_NO, whether or not to act as
 * a malicious node which sends out lots of PUTS
 */
static unsigned int malicious_putter;

/**
 * Frequency for malicious get requests.
 */
static unsigned long long malicious_get_frequency;

/**
 * Frequency for malicious put requests.
 */
static unsigned long long malicious_put_frequency;

/**
 * Reply times for requests, if we are busy, don't send any
 * more requests!
 */
static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];

/**
 * Current counter for replies.
 */
static unsigned int reply_counter;

/**
 * Forward declaration.
 */
static size_t send_generic_reply (void *cls, size_t size, void *buf);

/** Declare here so retry_core_send is aware of it */
size_t core_transmit_notify (void *cls,
                             size_t size, void *buf);

/**
 * Convert unique ID to hash code.
 *
 * @param uid unique ID to convert
 * @param hash set to uid (extended with zeros)
 */
static void
hash_from_uid (uint64_t uid,
               GNUNET_HashCode *hash)
{
  memset (hash, 0, sizeof(GNUNET_HashCode));
  *((uint64_t*)hash) = uid;
}

#if AVG
/**
 * Calculate the average send time between messages so that we can
 * ignore certain requests if we get too busy.
 *
 * @return the average time between asking core to send a message
 *         and when the buffer for copying it is passed
 */
static struct GNUNET_TIME_Relative get_average_send_delay()
{
  unsigned int i;
  unsigned int divisor;
  struct GNUNET_TIME_Relative average_time;
  average_time = GNUNET_TIME_relative_get_zero();
  divisor = 0;
  for (i = 0; i < MAX_REPLY_TIMES; i++)
  {
    average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
    if (reply_times[i].value == (uint64_t)0)
      continue;
    else
      divisor++;
  }
  if (divisor == 0)
  {
    return average_time;
  }

  average_time = GNUNET_TIME_relative_divide(average_time, divisor);
  fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
  return average_time;
}
#endif

/**
 * Given the largest send delay, artificially decrease it
 * so the next time around we may have a chance at sending
 * again.
 */
static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
{
  unsigned int i;
  for (i = 0; i < MAX_REPLY_TIMES; i++)
    {
      if (reply_times[i].value == max_time.value)
        {
          reply_times[i].value = reply_times[i].value / 2;
          return;
        }
    }
}

/**
 * Find the maximum send time of the recently sent values.
 *
 * @return the average time between asking core to send a message
 *         and when the buffer for copying it is passed
 */
static struct GNUNET_TIME_Relative get_max_send_delay()
{
  unsigned int i;
  struct GNUNET_TIME_Relative max_time;
  max_time = GNUNET_TIME_relative_get_zero();

  for (i = 0; i < MAX_REPLY_TIMES; i++)
  {
    if (reply_times[i].value > max_time.value)
      max_time.value = reply_times[i].value;
  }

  if (max_time.value > MAX_REQUEST_TIME.value)
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
  return max_time;
}

static void
increment_stats(const char *value)
{
  if (stats != NULL)
    {
      GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
    }
}

/**
 *  Try to send another message from our core send list
 */
static void
try_core_send (void *cls,
               const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct PeerInfo *peer = cls;
  struct P2PPendingMessage *pending;
  size_t ssize;

  peer->send_task = GNUNET_SCHEDULER_NO_TASK;

  if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
    return;

  if (peer->th != NULL)
    return; /* Message send already in progress */

  pending = peer->head;
  if (pending != NULL)
    {
      ssize = ntohs(pending->msg->size);
#if DEBUG_DHT > 1
     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
                "DHT", ssize, GNUNET_i2s(&peer->id));
#endif
      pending->scheduled = GNUNET_TIME_absolute_get();
      reply_counter++;
      if (reply_counter >= MAX_REPLY_TIMES)
	reply_counter = 0;
      peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
                                                   pending->timeout, &peer->id,
                                                   ssize, &core_transmit_notify, peer);
    }
}

/**
 * Function called to send a request out to another peer.
 * Called both for locally initiated requests and those
 * received from other peers.
 *
 * @param cls DHT service closure argument
 * @param msg the encapsulated message
 * @param peer the peer to forward the message to
 * @param msg_ctx the context of the message (hop count, bloom, etc.)
 */
static void 
forward_result_message (void *cls,
			const struct GNUNET_MessageHeader *msg,
			struct PeerInfo *peer,
			struct DHT_MessageContext *msg_ctx)
{
  struct GNUNET_DHT_P2PRouteResultMessage *result_message;
  struct P2PPendingMessage *pending;
  size_t msize;
  size_t psize;

  increment_stats(STAT_RESULT_FORWARDS);
  msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
  GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
  psize = sizeof(struct P2PPendingMessage) + msize;
  pending = GNUNET_malloc(psize);
  pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
  pending->importance = DHT_SEND_PRIORITY;
  pending->timeout = GNUNET_TIME_relative_get_forever();
  result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
  result_message->header.size = htons(msize);
  result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
  result_message->put_path_length = htons(0); /* FIXME: implement */
  result_message->get_path_length = htons(0); /* FIXME: implement */
  result_message->options = htonl(msg_ctx->msg_options);
  result_message->hop_count = htonl(msg_ctx->hop_count + 1);
  GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
  result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
  memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
  memcpy(&result_message[1], msg, ntohs(msg->size));
#if DEBUG_DHT > 1
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Adding pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
#endif
  GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
  if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
    peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
}
/**
 * Called when core is ready to send a message we asked for
 * out to the destination.
 *
 * @param cls closure (NULL)
 * @param size number of bytes available in buf
 * @param buf where the callee should write the message
 * @return number of bytes written to buf
 */
size_t core_transmit_notify (void *cls,
                             size_t size, void *buf)
{
  struct PeerInfo *peer = cls;
  char *cbuf = buf;
  struct P2PPendingMessage *pending;

  size_t off;
  size_t msize;

  if (buf == NULL)
    {
      /* client disconnected */
#if DEBUG_DHT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
#endif
      return 0;
    }

  if (peer->head == NULL)
    return 0;

  peer->th = NULL;
  off = 0;
  pending = peer->head;
  reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
  msize = ntohs(pending->msg->size);
  if (msize <= size)
    {
      off = msize;
      memcpy (cbuf, pending->msg, msize);
      GNUNET_CONTAINER_DLL_remove (peer->head,
                                   peer->tail,
                                   pending);
#if DEBUG_DHT > 1
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Removing pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
#endif
      GNUNET_free (pending);
    }
#if SMART
  while (NULL != pending &&
          (size - off >= (msize = ntohs (pending->msg->size))))
    {
#if DEBUG_DHT_ROUTING
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s:%s' : transmit_notify (core) called with size %d, available %d\n", my_short_id, "dht service", msize, size);
#endif
      memcpy (&cbuf[off], pending->msg, msize);
      off += msize;
      GNUNET_CONTAINER_DLL_remove (peer->head,
                                   peer->tail,
                                   pending);
      GNUNET_free (pending);
      pending = peer->head;
    }
#endif
  if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
    peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
#if DEBUG_DHT > 1
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s:%s' : transmit_notify (core) called with size %d, available %d, returning %d\n", my_short_id, "dht service", msize, size, off);
#endif
  return off;
}


/**
 * Compute the distance between have and target as a 32-bit value.
 * Differences in the lower bits must count stronger than differences
 * in the higher bits.
 *
 * @return 0 if have==target, otherwise a number
 *           that is larger as the distance between
 *           the two hash codes increases
 */
static unsigned int
distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
{
  unsigned int bucket;
  unsigned int msb;
  unsigned int lsb;
  unsigned int i;

  /* We have to represent the distance between two 2^9 (=512)-bit
     numbers as a 2^5 (=32)-bit number with "0" being used for the
     two numbers being identical; furthermore, we need to
     guarantee that a difference in the number of matching
     bits is always represented in the result.

     We use 2^32/2^9 numerical values to distinguish between
     hash codes that have the same LSB bit distance and
     use the highest 2^9 bits of the result to signify the
     number of (mis)matching LSB bits; if we have 0 matching
     and hence 512 mismatching LSB bits we return -1 (since
     512 itself cannot be represented with 9 bits) */

  /* first, calculate the most significant 9 bits of our
     result, aka the number of LSBs */
  bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
  /* bucket is now a value between 0 and 512 */
  if (bucket == 512)
    return 0;                   /* perfect match */
  if (bucket == 0)
    return (unsigned int) -1;   /* LSB differs; use max (if we did the bit-shifting
                                   below, we'd end up with max+1 (overflow)) */

  /* calculate the most significant bits of the final result */
  msb = (512 - bucket) << (32 - 9);
  /* calculate the 32-9 least significant bits of the final result by
     looking at the differences in the 32-9 bits following the
     mismatching bit at 'bucket' */
  lsb = 0;
  for (i = bucket + 1;
       (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
    {
      if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
        lsb |= (1 << (bucket + 32 - 9 - i));    /* first bit set will be 10,
                                                   last bit set will be 31 -- if
                                                   i does not reach 512 first... */
    }
  return msb | lsb;
}

/**
 * Return a number that is larger the closer the
 * "have" GNUNET_hash code is to the "target".
 *
 * @return inverse distance metric, non-zero.
 *         Must fudge the value if NO bits match.
 */
static unsigned int
inverse_distance (const GNUNET_HashCode * target,
                  const GNUNET_HashCode * have)
{
  if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
    return 1; /* Never return 0! */
  return ((unsigned int) -1) - distance (target, have);
}

/**
 * Find the optimal bucket for this key, regardless
 * of the current number of buckets in use.
 *
 * @param hc the hashcode to compare our identity to
 *
 * @return the proper bucket index, or GNUNET_SYSERR
 *         on error (same hashcode)
 */
static int find_bucket(const GNUNET_HashCode *hc)
{
  unsigned int bits;

  bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
  if (bits == MAX_BUCKETS)
    return GNUNET_SYSERR;
  return MAX_BUCKETS - bits - 1;
}

/**
 * Find which k-bucket this peer should go into,
 * taking into account the size of the k-bucket
 * array.  This means that if more bits match than
 * there are currently buckets, lowest_bucket will
 * be returned.
 *
 * @param hc GNUNET_HashCode we are finding the bucket for.
 *
 * @return the proper bucket index for this key,
 *         or GNUNET_SYSERR on error (same hashcode)
 */
static int find_current_bucket(const GNUNET_HashCode *hc)
{
  int actual_bucket;
  actual_bucket = find_bucket(hc);

  if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
    return lowest_bucket;
  else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
    return lowest_bucket;
  else
    return actual_bucket;
}

#if EXTRA_CHECKS
/**
 * Find a routing table entry from a peer identity
 *
 * @param peer the peer to look up
 *
 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
 */
static int
find_bucket_by_peer(const struct PeerInfo *peer)
{
  int bucket;
  struct PeerInfo *pos;

  for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
    {
      pos = k_buckets[bucket].head;
      while (pos != NULL)
        {
          if (peer == pos)
            return bucket;
          pos = pos->next;
        }
    }

  return GNUNET_SYSERR; /* No such peer. */
}
#endif

#if PRINT_TABLES
/**
 * Print the complete routing table for this peer.
 */
static void
print_routing_table ()
{
  int bucket;
  struct PeerInfo *pos;
  char char_buf[30000];
  int char_pos;
  memset(char_buf, 0, sizeof(char_buf));
  char_pos = 0;
  char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
  //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
  for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
    {
      pos = k_buckets[bucket].head;
      char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
      //fprintf(stderr, "Bucket %d:\n", bucket);
      while (pos != NULL)
        {
          //fprintf(stderr, "\tPeer %s, best bucket %d, %d bits match\n", GNUNET_i2s(&pos->id), find_bucket(&pos->id.hashPubKey), GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey));
          char_pos += sprintf(&char_buf[char_pos], "\tPeer %s, best bucket %d, %d bits match\n", GNUNET_i2s(&pos->id), find_bucket(&pos->id.hashPubKey), GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey));
          pos = pos->next;
        }
    }
  fprintf(stderr, "%s", char_buf);
  fflush(stderr);
}
#endif

/**
 * Find a routing table entry from a peer identity
 *
 * @param peer the peer identity to look up
 *
 * @return the routing table entry, or NULL if not found
 */
static struct PeerInfo *
find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
{
  int bucket;
  struct PeerInfo *pos;
  bucket = find_current_bucket(&peer->hashPubKey);

  if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
    return NULL;

  pos = k_buckets[bucket].head;
  while (pos != NULL)
    {
      if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
        return pos;
      pos = pos->next;
    }
  return NULL; /* No such peer. */
}

/* Forward declaration */
static void
update_core_preference (void *cls,
                        const struct GNUNET_SCHEDULER_TaskContext *tc);
/**
 * Function called with statistics about the given peer.
 *
 * @param cls closure
 * @param peer identifies the peer
 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
 * @param bpm_out set to the current bandwidth limit (sending) for this peer
 * @param amount set to the amount that was actually reserved or unreserved;
 *               either the full requested amount or zero (no partial reservations)
 * @param preference current traffic preference for the given peer
 */
static void
update_core_preference_finish (void *cls,
                               const struct GNUNET_PeerIdentity * peer,
                               struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
                               struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
                               int amount, uint64_t preference)
{
  struct PeerInfo *peer_info = cls;
  peer_info->info_ctx = NULL;
  GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
}

static void
update_core_preference (void *cls,
                        const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct PeerInfo *peer = cls;
  uint64_t preference;
  unsigned int matching;
  if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
    {
      return;
    }
  matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
  if (matching >= 64)
    {
      GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
      matching = 63;
    }
  preference = 1LL << matching;
  peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
                                                       &peer->id,
                                                       GNUNET_TIME_relative_get_forever(),
                                                       GNUNET_BANDWIDTH_value_init (UINT32_MAX),
                                                       0,
                                                       preference,
                                                       &update_core_preference_finish,
                                                       peer);
}

/**
 * Really add a peer to a bucket (only do assertions
 * on size, etc.)
 *
 * @param peer GNUNET_PeerIdentity of the peer to add
 * @param bucket the already figured out bucket to add
 *        the peer to
 * @param latency the core reported latency of this peer
 * @param distance the transport level distance to this peer
 *
 * @return the newly added PeerInfo
 */
static struct PeerInfo *
add_peer(const struct GNUNET_PeerIdentity *peer,
         unsigned int bucket,
         struct GNUNET_TIME_Relative latency,
         unsigned int distance)
{
  struct PeerInfo *new_peer;
  GNUNET_assert(bucket < MAX_BUCKETS);
  GNUNET_assert(peer != NULL);
  new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
  new_peer->latency = latency;
  new_peer->distance = distance;

  memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));

  GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
                                    k_buckets[bucket].tail,
                                    k_buckets[bucket].tail,
                                    new_peer);
  k_buckets[bucket].peers_size++;

  if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
    {
#if DO_UPDATE_PREFERENCE
      new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
#endif
    }

  return new_peer;
}

/**
 * Given a peer and its corresponding bucket,
 * remove it from that bucket.  Does not free
 * the PeerInfo struct, nor cancel messages
 * or free messages waiting to be sent to this
 * peer!
 *
 * @param peer the peer to remove
 * @param bucket the bucket the peer belongs to
 */
static void remove_peer (struct PeerInfo *peer,
                         unsigned int bucket)
{
  GNUNET_assert(k_buckets[bucket].peers_size > 0);
  GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
                              k_buckets[bucket].tail,
                              peer);
  k_buckets[bucket].peers_size--;
#if CHANGE_LOWEST
  if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
    lowest_bucket++;
#endif
}

/**
 * Removes peer from a bucket, then frees associated
 * resources and frees peer.
 *
 * @param peer peer to be removed and freed
 * @param bucket which bucket this peer belongs to
 */
static void delete_peer (struct PeerInfo *peer,
                         unsigned int bucket)
{
  struct P2PPendingMessage *pos;
  struct P2PPendingMessage *next;
#if EXTRA_CHECKS
  struct PeerInfo *peer_pos;

  peer_pos = k_buckets[bucket].head;
  while ((peer_pos != NULL) && (peer_pos != peer))
    peer_pos = peer_pos->next;
  if (peer_pos == NULL)
    {
      GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
      GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Lowest bucket: %d, find_current_bucket: %d, peer resides in bucket: %d\n", my_short_id, "DHT", lowest_bucket, find_current_bucket(&peer->id.hashPubKey), find_bucket_by_peer(peer));
    }
  GNUNET_assert(peer_pos != NULL);
#endif
  remove_peer(peer, bucket); /* First remove the peer from its bucket */

  if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
    GNUNET_SCHEDULER_cancel(sched, peer->send_task);
  if (peer->th != NULL)
    GNUNET_CORE_notify_transmit_ready_cancel(peer->th);

  pos = peer->head;
  while (pos != NULL) /* Remove any pending messages for this peer */
    {
      next = pos->next;
      GNUNET_free(pos);
      pos = next;
    }

  GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
  GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
  GNUNET_free(peer);
}


/**
 * Iterator over hash map entries.
 *
 * @param cls closure
 * @param key current key code
 * @param value PeerInfo of the peer to move to new lowest bucket
 * @return GNUNET_YES if we should continue to
 *         iterate,
 *         GNUNET_NO if not.
 */
static int move_lowest_bucket (void *cls,
                               const GNUNET_HashCode * key,
                               void *value)
{
  struct PeerInfo *peer = value;
  int new_bucket;

  GNUNET_assert(lowest_bucket > 0);
  new_bucket = lowest_bucket - 1;
  remove_peer(peer, lowest_bucket);
  GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
                                    k_buckets[new_bucket].tail,
                                    k_buckets[new_bucket].tail,
                                    peer);
  k_buckets[new_bucket].peers_size++;
  return GNUNET_YES;
}


/**
 * The current lowest bucket is full, so change the lowest
 * bucket to the next lower down, and move any appropriate
 * entries in the current lowest bucket to the new bucket.
 */
static void enable_next_bucket()
{
  struct GNUNET_CONTAINER_MultiHashMap *to_remove;
  struct PeerInfo *pos;
  GNUNET_assert(lowest_bucket > 0);
  to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
  pos = k_buckets[lowest_bucket].head;

#if PRINT_TABLES
  fprintf(stderr, "Printing RT before new bucket\n");
  print_routing_table();
#endif
  /* Populate the array of peers which should be in the next lowest bucket */
  while (pos != NULL)
    {
      if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
        GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
      pos = pos->next;
    }

  /* Remove peers from lowest bucket, insert into next lowest bucket */
  GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
  GNUNET_CONTAINER_multihashmap_destroy(to_remove);
  lowest_bucket = lowest_bucket - 1;
#if PRINT_TABLES
  fprintf(stderr, "Printing RT after new bucket\n");
  print_routing_table();
#endif
}

/**
 * Find the closest peer in our routing table to the
 * given hashcode.
 *
 * @return The closest peer in our routing table to the
 *         key, or NULL on error.
 */
static struct PeerInfo *
find_closest_peer (const GNUNET_HashCode *hc)
{
  struct PeerInfo *pos;
  struct PeerInfo *current_closest;
  unsigned int lowest_distance;
  unsigned int temp_distance;
  int bucket;
  int count;

  lowest_distance = -1;

  if (k_buckets[lowest_bucket].peers_size == 0)
    return NULL;

  current_closest = NULL;
  for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
    {
      pos = k_buckets[bucket].head;
      count = 0;
      while ((pos != NULL) && (count < bucket_size))
        {
          temp_distance = distance(&pos->id.hashPubKey, hc);
          if (temp_distance <= lowest_distance)
            {
              lowest_distance = temp_distance;
              current_closest = pos;
            }
          pos = pos->next;
          count++;
        }
    }
  GNUNET_assert(current_closest != NULL);
  return current_closest;
}


/**
 * Function called to send a request out to another peer.
 * Called both for locally initiated requests and those
 * received from other peers.
 *
 * @param cls DHT service closure argument (unused)
 * @param msg the encapsulated message
 * @param peer the peer to forward the message to
 * @param msg_ctx the context of the message (hop count, bloom, etc.)
 */
static void forward_message (void *cls,
                             const struct GNUNET_MessageHeader *msg,
                             struct PeerInfo *peer,
                             struct DHT_MessageContext *msg_ctx)
{
  struct GNUNET_DHT_P2PRouteMessage *route_message;
  struct P2PPendingMessage *pending;
  size_t msize;
  size_t psize;

  increment_stats(STAT_ROUTE_FORWARDS);

  if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
    increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);

  msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
  GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
  psize = sizeof(struct P2PPendingMessage) + msize;
  pending = GNUNET_malloc(psize);
  pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
  pending->importance = msg_ctx->importance;
  pending->timeout = msg_ctx->timeout;
  route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
  route_message->header.size = htons(msize);
  route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
  route_message->options = htonl(msg_ctx->msg_options);
  route_message->hop_count = htonl(msg_ctx->hop_count + 1);
  route_message->network_size = htonl(msg_ctx->network_size);
  route_message->desired_replication_level = htonl(msg_ctx->replication);
  route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
  if (msg_ctx->bloom != NULL)
    GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
  memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
  memcpy(&route_message[1], msg, ntohs(msg->size));
#if DEBUG_DHT > 1
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Adding pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
#endif
  GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
  if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
    peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
}

#if DO_PING
/**
 * Task used to send ping messages to peers so that
 * they don't get disconnected.
 *
 * @param cls the peer to send a ping message to
 * @param tc context, reason, etc.
 */
static void
periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct PeerInfo *peer = cls;
  struct GNUNET_MessageHeader ping_message;
  struct DHT_MessageContext message_context;

  if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
    return;

  ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
  ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);

  memset(&message_context, 0, sizeof(struct DHT_MessageContext));
#if DEBUG_PING
  GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
#endif
  forward_message(NULL, &ping_message, peer, &message_context);
  peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
}

/**
 * Schedule PING messages for the top X peers in each
 * bucket of the routing table (so core won't disconnect them!)
 */
void schedule_ping_messages()
{
  unsigned int bucket;
  unsigned int count;
  struct PeerInfo *pos;
  for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
    {
      pos = k_buckets[bucket].head;
      count = 0;
      while (pos != NULL)
        {
          if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
            GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
          else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
            {
              GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
              pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
            }
          pos = pos->next;
          count++;
        }
    }
}
#endif

/**
 * Attempt to add a peer to our k-buckets.
 *
 * @param peer the peer identity of the peer being added
 * @param bucket the bucket that we want this peer to go in
 * @param latency transport latency of this peer
 * @param distance transport distance to this peer
 *
 * @return NULL if the peer was not added,
 *         pointer to PeerInfo for new peer otherwise
 */
static struct PeerInfo *
try_add_peer(const struct GNUNET_PeerIdentity *peer,
             unsigned int bucket,
             struct GNUNET_TIME_Relative latency,
             unsigned int distance)
{
  int peer_bucket;
  struct PeerInfo *new_peer;

  if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
    return NULL;

  peer_bucket = find_current_bucket(&peer->hashPubKey);

  GNUNET_assert(peer_bucket >= lowest_bucket);
  new_peer = add_peer(peer, peer_bucket, latency, distance);

  if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
    enable_next_bucket();
#if DO_PING
  schedule_ping_messages();
#endif
  return new_peer;
}


/**
 * Task run to check for messages that need to be sent to a client.
 *
 * @param client a ClientList, containing the client and any messages to be sent to it
 */
static void
process_pending_messages (struct ClientList *client)
{ 
  if (client->pending_head == NULL) 
    return;    
  if (client->transmit_handle != NULL) 
    return;

  client->transmit_handle =
    GNUNET_SERVER_notify_transmit_ready (client->client_handle,
					 ntohs (client->pending_head->msg->
						size),
					 GNUNET_TIME_UNIT_FOREVER_REL,
					 &send_generic_reply, client);
}

/**
 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
 * request.  A ClientList is passed as closure, take the head of the list
 * and copy it into buf, which has the result of sending the message to the
 * client.
 *
 * @param cls closure to this call
 * @param size maximum number of bytes available to send
 * @param buf where to copy the actual message to
 *
 * @return the number of bytes actually copied, 0 indicates failure
 */
static size_t
send_generic_reply (void *cls, size_t size, void *buf)
{
  struct ClientList *client = cls;
  char *cbuf = buf;
  struct PendingMessage *reply;
  size_t off;
  size_t msize;

  client->transmit_handle = NULL;
  if (buf == NULL)             
    {
      /* client disconnected */
      return 0;
    }
  off = 0;
  while ( (NULL != (reply = client->pending_head)) &&
	  (size >= off + (msize = ntohs (reply->msg->size))))
    {
      GNUNET_CONTAINER_DLL_remove (client->pending_head,
				   client->pending_tail,
				   reply);
      memcpy (&cbuf[off], reply->msg, msize);
      GNUNET_free (reply);
      off += msize;
    }
  process_pending_messages (client);
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Transmitted %u bytes of replies to client\n",
	      (unsigned int) off);
#endif
  return off;
}


/**
 * Add a PendingMessage to the clients list of messages to be sent
 *
 * @param client the active client to send the message to
 * @param pending_message the actual message to send
 */
static void
add_pending_message (struct ClientList *client,
                     struct PendingMessage *pending_message)
{
  GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
				     client->pending_tail,
				     client->pending_tail,
				     pending_message);
  process_pending_messages (client);
}




/**
 * Called when a reply needs to be sent to a client, as
 * a result it found to a GET or FIND PEER request.
 *
 * @param client the client to send the reply to
 * @param message the encapsulated message to send
 * @param uid the unique identifier of this request
 */
static void
send_reply_to_client (struct ClientList *client,
                      const struct GNUNET_MessageHeader *message,
                      unsigned long long uid,
		      const GNUNET_HashCode *key)
{
  struct GNUNET_DHT_RouteResultMessage *reply;
  struct PendingMessage *pending_message;
  uint16_t msize;
  size_t tsize;
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
#endif
  msize = ntohs (message->size);
  tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
  if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
    {
      GNUNET_break_op (0);
      return;
    }
  pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
  pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
  reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
  reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
  reply->header.size = htons (tsize);
  reply->put_path_length = htons(0); /* FIXME: implement */
  reply->get_path_length = htons(0); /* FIXME: implement */
  reply->unique_id = GNUNET_htonll (uid);
  reply->key = *key;
  memcpy (&reply[1], message, msize);
  add_pending_message (client, pending_message);
}

/**
 * Consider whether or not we would like to have this peer added to
 * our routing table.  Check whether bucket for this peer is full,
 * if so return negative; if not return positive.  Since peers are
 * only added on CORE level connect, this doesn't actually add the
 * peer to the routing table.
 *
 * @param peer the peer we are considering adding
 *
 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
 *         already full)
 */
static int consider_peer (struct GNUNET_PeerIdentity *peer)
{
  int bucket;

  if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
    return GNUNET_NO; /* We already know this peer (are connected even!) */
  bucket = find_current_bucket(&peer->hashPubKey);

  if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
    return GNUNET_YES;

  return GNUNET_NO;
}

/**
 * Main function that handles whether or not to route a result
 * message to other peers, or to send to our local client.
 *
 * @param cls closure (unused, always should be NULL)
 * @param msg the result message to be routed
 * @param message_context context of the message we are routing
 *
 * @return the number of peers the message was routed to,
 *         GNUNET_SYSERR on failure
 */
static int route_result_message(void *cls,
                                struct GNUNET_MessageHeader *msg,
                                struct DHT_MessageContext *message_context)
{
  struct GNUNET_PeerIdentity new_peer;
  struct DHTQueryRecord *record;
  struct DHTRouteSource *pos;
  struct PeerInfo *peer_info;
  const struct GNUNET_MessageHeader *hello_msg;

  increment_stats(STAT_RESULTS);
  /**
   * If a find peer result message is received and contains a valid
   * HELLO for another peer, offer it to the transport service.
   */
  if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
    {
      if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
        GNUNET_break_op(0);

      hello_msg = &msg[1];
      if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
      {
        GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
        GNUNET_break_op(0);
        return GNUNET_NO;
      }
      else /* We have a valid hello, and peer id stored in new_peer */
      {
        find_peer_context.count++;
        increment_stats(STAT_FIND_PEER_REPLY);
        if (GNUNET_YES == consider_peer(&new_peer))
        {
          increment_stats(STAT_HELLOS_PROVIDED);
          GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
          GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
        }
      }
    }

  if (malicious_dropper == GNUNET_YES)
    record = NULL;
  else
    record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);

  if (record == NULL) /* No record of this message! */
    {
#if DEBUG_DHT
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
                "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
#endif
#if DEBUG_DHT_ROUTING
      if ((debug_routes_extended) && (dhtlog_handle != NULL))
        {
          dhtlog_handle->insert_route (NULL,
                                       message_context->unique_id,
                                       DHTLOG_RESULT,
                                       message_context->hop_count,
                                       GNUNET_SYSERR,
                                       &my_identity,
                                       &message_context->key,
                                       message_context->peer, NULL);
        }
#endif
      if (message_context->bloom != NULL)
        {
          GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
          message_context->bloom = NULL;
        }
      return 0;
    }

  pos = record->head;
  while (pos != NULL)
    {
#if STRICT_FORWARDING
      if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
        {
          if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
          {
            increment_stats("# find peer responses NOT forwarded (bloom match)");
            pos = pos->next;
            continue;
          }
          else
            GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
        }
#endif

      if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
        {
#if DEBUG_DHT
          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                      "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
                      "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
#endif
#if DEBUG_DHT_ROUTING
          if ((debug_routes_extended) && (dhtlog_handle != NULL))
            {
              dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
                                           message_context->hop_count,
                                           GNUNET_YES, &my_identity, &message_context->key,
                                           message_context->peer, NULL);
            }
#endif
          increment_stats(STAT_RESULTS_TO_CLIENT);
          if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
            increment_stats(STAT_GET_REPLY);

          send_reply_to_client(pos->client, msg, 
			       message_context->unique_id,
			       &message_context->key);
        }
      else /* Send to peer */
        {
          peer_info = find_peer_by_id(&pos->source);
          if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
            {
              pos = pos->next;
              continue;
            }

          if (message_context->bloom == NULL)
            message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
          GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
          if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
            {
#if DEBUG_DHT
              GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                          "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
                          "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
#endif
#if DEBUG_DHT_ROUTING
              if ((debug_routes_extended) && (dhtlog_handle != NULL))
                {
                  dhtlog_handle->insert_route (NULL, message_context->unique_id,
                                               DHTLOG_RESULT,
                                               message_context->hop_count,
                                               GNUNET_NO, &my_identity, &message_context->key,
                                               message_context->peer, &pos->source);
                }
#endif
              forward_result_message(cls, msg, peer_info, message_context);
            }
          else
            {
#if DEBUG_DHT
              GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                          "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
                          "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
#endif
            }
        }
      pos = pos->next;
    }
  if (message_context->bloom != NULL)
    GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
  return 0;
}

/**
 * Iterator for local get request results,
 *
 * @param cls closure for iterator, a DatacacheGetContext
 * @param exp when does this value expire?
 * @param key the key this data is stored under
 * @param size the size of the data identified by key
 * @param data the actual data
 * @param type the type of the data
 *
 * @return GNUNET_OK to continue iteration, anything else
 * to stop iteration.
 */
static int
datacache_get_iterator (void *cls,
                        struct GNUNET_TIME_Absolute exp,
                        const GNUNET_HashCode * key,
                        uint32_t size, const char *data, uint32_t type)
{
  struct DHT_MessageContext *msg_ctx = cls;
  struct DHT_MessageContext *new_msg_ctx;
  struct GNUNET_DHT_GetResultMessage *get_result;
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
#endif
  new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
  memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
  get_result =
    GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
  get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
  get_result->header.size =
    htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
  get_result->expiration = GNUNET_TIME_absolute_hton(exp);
  get_result->type = htons (type);
  memcpy (&get_result[1], data, size);
  new_msg_ctx->peer = &my_identity;
  new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
  new_msg_ctx->hop_count = 0;
  new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
  new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
  increment_stats(STAT_GET_RESPONSE_START);
  route_result_message(cls, &get_result->header, new_msg_ctx);
  GNUNET_free(new_msg_ctx);
  //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
  //                      datacache_get_ctx->unique_id);
  GNUNET_free (get_result);
  return GNUNET_OK;
}


/**
 * Server handler for all dht get requests, look for data,
 * if found, send response either to clients or other peers.
 *
 * @param cls closure for service
 * @param msg the actual get message
 * @param message_context struct containing pertinent information about the get request
 *
 * @return number of items found for GET request
 */
static unsigned int
handle_dht_get (void *cls, 
		const struct GNUNET_MessageHeader *msg,
                struct DHT_MessageContext *message_context)
{
  const struct GNUNET_DHT_GetMessage *get_msg;
  uint16_t get_type;
  uint16_t bf_size;
  uint16_t msize;
  uint16_t xquery_size;
  unsigned int results;
  struct GNUNET_CONTAINER_BloomFilter *bf;
  const void *xquery;
  const char *end;

  msize = ntohs (msg->size);
  if (msize < sizeof (struct GNUNET_DHT_GetMessage))
    {
      GNUNET_break (0);
      return 0;
    }
  get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
  bf_size = ntohs (get_msg->bf_size);
  xquery_size = ntohs (get_msg->xquery_size);
  if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + xquery_size)
    {
      GNUNET_break (0);
      return 0;
    }
  end = (const char*) &get_msg[1];
  if (xquery_size == 0)
    {
      xquery = NULL;
    }
  else
    {
      xquery = (const void*) end;
      end += xquery_size;
    }
  if (bf_size == 0)
    {
      bf = NULL;
    }
  else
    {
      bf = GNUNET_CONTAINER_bloomfilter_init (end,
					      bf_size,
					      GNUNET_DHT_GET_BLOOMFILTER_K);
    }

  get_type = ntohs (get_msg->type);
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
	      my_short_id,
              "DHT", "GET", 
	      get_type,
	      GNUNET_h2s (&message_context->key),
              message_context->unique_id);
#endif
  increment_stats(STAT_GETS);
  results = 0;
#if HAVE_MALICIOUS
  if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
    {
      GNUNET_CONTAINER_bloomfilter_free (bf);
      return results;
    }
#endif
  /* FIXME: put xquery / bf into message_context and use
     them for processing! */
  if (datacache != NULL)
    results
      = GNUNET_DATACACHE_get (datacache,
			      &message_context->key, get_type,
			      &datacache_get_iterator,
			      message_context);

  if (results >= 1)
    {
#if DEBUG_DHT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
                  results, "GET", message_context->unique_id);
#endif
#if DEBUG_DHT_ROUTING
      if ((debug_routes) && (dhtlog_handle != NULL))
        {
          dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
                                message_context->hop_count, GNUNET_YES, &my_identity,
                                &message_context->key);
        }

      if ((debug_routes_extended) && (dhtlog_handle != NULL))
        {
          dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
                                       message_context->hop_count, GNUNET_YES,
                                       &my_identity, &message_context->key, message_context->peer,
                                       NULL);
        }
#endif
    }

  if (message_context->hop_count == 0) /* Locally initiated request */
    {
#if DEBUG_DHT_ROUTING
    if ((debug_routes) && (dhtlog_handle != NULL))
      {
        dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
                                      message_context->hop_count, GNUNET_NO, &my_identity,
                                      &message_context->key);
      }
#endif
    }
  GNUNET_CONTAINER_bloomfilter_free (bf);
  return results;
}

static void
remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  GNUNET_HashCode *key = cls;
  if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
    {
      GNUNET_free(key);
    }
}

/**
 * Server handler for initiating local dht find peer requests
 *
 * @param cls closure for service
 * @param find_msg the actual find peer message
 * @param message_context struct containing pertinent information about the request
 *
 */
static void
handle_dht_find_peer (void *cls,
                      const struct GNUNET_MessageHeader *find_msg,
                      struct DHT_MessageContext *message_context)
{
  struct GNUNET_MessageHeader *find_peer_result;
  struct GNUNET_DHT_FindPeerMessage *find_peer_message;
  struct DHT_MessageContext *new_msg_ctx;
  struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
  size_t hello_size;
  size_t tsize;
  GNUNET_HashCode *recent_hash;
  struct GNUNET_MessageHeader *other_hello;
  size_t other_hello_size;
  struct GNUNET_PeerIdentity peer_id;

  find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
  GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
  if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
    return;
  other_hello = NULL;
  other_hello_size = 0;
  if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
    {
      other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
      other_hello = GNUNET_malloc(other_hello_size);
      memcpy(other_hello, &find_peer_message[1], other_hello_size);
      if ((GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)other_hello) == 0) || (GNUNET_OK != GNUNET_HELLO_get_id((struct GNUNET_HELLO_Message *)other_hello, &peer_id)))
        {
          GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
          GNUNET_free(other_hello);
          return;
        }
#if FIND_PEER_WITH_HELLO
      if (GNUNET_YES == consider_peer(&peer_id))
        {
          increment_stats(STAT_HELLOS_PROVIDED);
          GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
          GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
          return;
        }
      else /* We don't want this peer! */
        return;
#endif
    }

#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
              my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&message_context->key),
              ntohs (find_msg->size),
              sizeof (struct GNUNET_MessageHeader));
#endif
  if (my_hello == NULL)
  {
#if DEBUG_DHT
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "`%s': Our HELLO is null, can't return.\n",
                "DHT");
#endif
    GNUNET_free_non_null(other_hello);
    return;
  }

  incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
  if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
    {
      increment_stats(STAT_BLOOM_FIND_PEER);
      GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
      GNUNET_free_non_null(other_hello);
      return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
    }
  GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);

#if RESTRICT_FIND_PEER

  /**
   * Ignore any find peer requests from a peer we have seen very recently.
   */
  if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent_find_peer_requests, &message_context->key)) /* We have recently responded to a find peer request for this peer! */
  {
    increment_stats("# dht find peer requests ignored (recently seen!)");
    GNUNET_free_non_null(other_hello);
    return;
  }

  /**
   * Use this check to only allow the peer to respond to find peer requests if
   * it would be beneficial to have the requesting peer in this peers routing
   * table.  Can be used to thwart peers flooding the network with find peer
   * requests that we don't care about.  However, if a new peer is joining
   * the network and has no other peers this is a problem (assume all buckets
   * full, no one will respond!).
   */
  memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
  if (GNUNET_NO == consider_peer(&peer_id))
    {
      increment_stats("# dht find peer requests ignored (do not need!)");
      GNUNET_free_non_null(other_hello);
      return;
    }
#endif

  recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
  memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
  GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
  GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);

  /* Simplistic find_peer functionality, always return our hello */
  hello_size = ntohs(my_hello->size);
  tsize = hello_size + sizeof (struct GNUNET_MessageHeader);

  if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
    {
      GNUNET_break_op (0);
      GNUNET_free_non_null(other_hello);
      return;
    }

  find_peer_result = GNUNET_malloc (tsize);
  find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
  find_peer_result->size = htons (tsize);
  memcpy (&find_peer_result[1], my_hello, hello_size);

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s': Sending hello size %d to requesting peer.\n",
              "DHT", hello_size);

  new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
  memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
  new_msg_ctx->peer = &my_identity;
  new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
  new_msg_ctx->hop_count = 0;
  new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
  new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
  increment_stats(STAT_FIND_PEER_ANSWER);
  route_result_message(cls, find_peer_result, new_msg_ctx);
  GNUNET_free(new_msg_ctx);
#if DEBUG_DHT_ROUTING
  if ((debug_routes) && (dhtlog_handle != NULL))
    {
      dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
                                   message_context->hop_count, GNUNET_YES, &my_identity,
                                   &message_context->key);
    }
#endif
  GNUNET_free_non_null(other_hello);
  GNUNET_free(find_peer_result);
}

/**
 * Task used to republish data.
 * Forward declaration; function call loop.
 *
 * @param cls closure (a struct RepublishContext)
 * @param tc runtime context for this task
 */
static void
republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);

/**
 * Server handler for initiating local dht put requests
 *
 * @param cls closure for service
 * @param msg the actual put message
 * @param message_context struct containing pertinent information about the request
 */
static void
handle_dht_put (void *cls,
		const struct GNUNET_MessageHeader *msg,
                struct DHT_MessageContext *message_context)
{
  struct GNUNET_DHT_PutMessage *put_msg;
  size_t put_type;
  size_t data_size;
  int ret;
  struct RepublishContext *put_context;

  GNUNET_assert (ntohs (msg->size) >=
                 sizeof (struct GNUNET_DHT_PutMessage));


  put_msg = (struct GNUNET_DHT_PutMessage *)msg;
  put_type = ntohs (put_msg->type);

  if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
    return;

  data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
              my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
#endif
#if DEBUG_DHT_ROUTING
  if (message_context->hop_count == 0) /* Locally initiated request */
    {
      if ((debug_routes) && (dhtlog_handle != NULL))
        {
          dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
                                       message_context->hop_count, GNUNET_NO, &my_identity,
                                       &message_context->key);
        }
    }
#endif

  if (message_context->closest != GNUNET_YES)
    return;

#if DEBUG_DHT_ROUTING
  if ((debug_routes_extended) && (dhtlog_handle != NULL))
    {
      dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
                                   message_context->hop_count, GNUNET_YES,
                                   &my_identity, &message_context->key, message_context->peer,
                                   NULL);
    }

  if ((debug_routes) && (dhtlog_handle != NULL))
    {
      dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
                                   message_context->hop_count, GNUNET_YES, &my_identity,
                                   &message_context->key);
    }
#endif

  increment_stats(STAT_PUTS_INSERTED);
  if (datacache != NULL)
    {
      ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
                                  (char *) &put_msg[1], put_type,
                                  GNUNET_TIME_absolute_ntoh(put_msg->expiration));

      if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
        {
          put_context = GNUNET_malloc(sizeof(struct RepublishContext));
          memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
          put_context->type = put_type;
          GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
        }
    }
  else
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "`%s:%s': %s request received, but have no datacache!\n",
                my_short_id, "DHT", "PUT");
}

/**
 * Estimate the diameter of the network based
 * on how many buckets are currently in use.
 * Concept here is that the diameter of the network
 * is roughly the distance a message must travel in
 * order to reach its intended destination.  Since
 * at each hop we expect to get one bit closer, and
 * we have one bit per bucket, the number of buckets
 * in use should be the largest number of hops for
 * a sucessful message. (of course, this assumes we
 * know all peers in the network!)
 *
 * @return ballpark diameter figure
 */
static unsigned int estimate_diameter()
{
  return MAX_BUCKETS - lowest_bucket;
}

/**
 * To how many peers should we (on average)
 * forward the request to obtain the desired
 * target_replication count (on average).
 *
 * Always 0, 1 or 2 (don't send, send once, split)
 */
static unsigned int
get_forward_count (unsigned int hop_count, size_t target_replication)
{
#if DOUBLE
  double target_count;
  double random_probability;
#else
  uint32_t random_value;
#endif
  unsigned int target_value;
  unsigned int diameter;

  /**
   * If we are behaving in strict kademlia mode, send multiple initial requests,
   * but then only send to 1 or 0 peers based strictly on the number of hops.
   */
  if (strict_kademlia == GNUNET_YES)
    {
      if (hop_count == 0)
        return DHT_KADEMLIA_REPLICATION;
      else if (hop_count < max_hops)
        return 1;
      else
        return 0;
    }

  /* FIXME: the smaller we think the network is the more lenient we should be for
   * routing right?  The estimation below only works if we think we have reasonably
   * full routing tables, which for our RR topologies may not be the case!
   */
  diameter = estimate_diameter ();
  if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
    {
#if DEBUG_DHT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
                  "DHT", estimate_diameter(), lowest_bucket);
#endif
      return 0;
    }
  else if (hop_count > max_hops)
    {
#if DEBUG_DHT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
                  "DHT");
#endif
      return 0;
    }

#if DOUBLE
  GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
  GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
  target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
    (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
  GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
  random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
      RAND_MAX)) / RAND_MAX;
  GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);

  target_value = 0;
  //while (target_value < target_count)
  if (target_value < target_count)
    target_value++; /* target_value is ALWAYS 1 after this "loop", right?  Because target_count is always > 0, right?  Or does it become 0.00000... at some point because the hop count is so high? */


  //if ((target_count + 1 - (double)target_value) > random_probability)
  if ((target_count) > random_probability)
    target_value++;
#endif

  random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "replication %u, at hop %d, will split with probability %f\n", target_replication, hop_count, target_replication / (double)((target_replication * (hop_count + 1) + diameter) + 1));
  target_value = 1;
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
  if (random_value < target_replication)
    target_value++;

  return target_value;
}

/*
 * Check whether my identity is closer than any known peers.
 * If a non-null bloomfilter is given, check if this is the closest
 * peer that hasn't already been routed to.
 *
 * @param target hash code to check closeness to
 * @param bloom bloomfilter, exclude these entries from the decision
 *
 * Return GNUNET_YES if node location is closest, GNUNET_NO
 * otherwise.
 */
int
am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
{
  int bits;
  int other_bits;
  int bucket_num;
  int count;
  struct PeerInfo *pos;
  unsigned int my_distance;

  if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
    return GNUNET_YES;

  bucket_num = find_current_bucket(target);

  bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
  my_distance = distance(&my_identity.hashPubKey, target);
  pos = k_buckets[bucket_num].head;
  count = 0;
  while ((pos != NULL) && (count < bucket_size))
    {
      if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
        {
          pos = pos->next;
          continue; /* Skip already checked entries */
        }

      other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
      if (other_bits > bits)
        return GNUNET_NO;
      else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
        {
          if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
            return GNUNET_YES;
          else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
            return GNUNET_NO;
        }
      pos = pos->next;
    }

#if DEBUG_TABLE
  GNUNET_GE_LOG (coreAPI->ectx,
                 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
                 GNUNET_GE_BULK, "closest peer\n");
  printPeerBits (&closest);
  GNUNET_GE_LOG (coreAPI->ectx,
                 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
                 GNUNET_GE_BULK, "me\n");
  printPeerBits (coreAPI->my_identity);
  GNUNET_GE_LOG (coreAPI->ectx,
                 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
                 GNUNET_GE_BULK, "key\n");
  printKeyBits (target);
  GNUNET_GE_LOG (coreAPI->ectx,
                 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
                 GNUNET_GE_BULK,
                 "closest peer inverse distance is %u, mine is %u\n",
                 inverse_distance (target, &closest.hashPubKey),
                 inverse_distance (target,
                                   &coreAPI->my_identity->hashPubKey));
#endif

  /* No peers closer, we are the closest! */
  return GNUNET_YES;
}


/**
 * Return this peers adjusted value based on the convergence
 * function chosen.  This is the key function for randomized
 * routing decisions.
 *
 * @param target the key of the request
 * @param peer the peer we would like the value of
 * @param hops number of hops this message has already traveled
 *
 * @return bit distance from target to peer raised to an exponent
 *         adjusted based on the current routing convergence algorithm
 *
 */
unsigned long long
converge_distance (const GNUNET_HashCode *target,
                   struct PeerInfo *peer,
                   unsigned int hops)
{
  unsigned long long ret;
  unsigned int other_matching_bits;
  double converge_modifier = 0.0;
  double base_converge_modifier = .1;
  double calc_value;
  double exponent;
  int curr_max_hops;

  if (use_max_hops)
    curr_max_hops = max_hops;
  else
    curr_max_hops = (estimate_diameter() + 1) * 2;

  if (converge_modifier > 0)
    converge_modifier = converge_modifier * base_converge_modifier;
  else
    {
      converge_modifier = base_converge_modifier;
      base_converge_modifier = 0.0;
    }

  GNUNET_assert(converge_modifier > 0);

  other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);

  switch (converge_option)
    {
      case DHT_CONVERGE_RANDOM:
        return 1; /* Always return 1, choose equally among all peers */
      case DHT_CONVERGE_LINEAR:
        calc_value = hops * curr_max_hops * converge_modifier;
        break;
      case DHT_CONVERGE_SQUARE:
        /**
         * Simple square based curve.
         */
        calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * converge_modifier));
        break;
      case DHT_CONVERGE_EXPONENTIAL:
        /**
         * Simple exponential curve.
         */
        if (base_converge_modifier > 0)
          calc_value = (converge_modifier * hops * hops) / curr_max_hops;
        else
          calc_value = (hops * hops) / curr_max_hops;
        break;
      default:
        return 1;
    }

  /* Take the log (base e) of the number of bits matching the other peer */
  exponent = log(other_matching_bits);

  /* Check if we would overflow; our largest possible value is 2^64 = e^44.361419555836498 */
  if (exponent * calc_value >= 44.361419555836498)
    return ULLONG_MAX;

  /* Clear errno and all math exceptions */
  errno = 0;
  feclearexcept(FE_ALL_EXCEPT);
  ret = (unsigned long long)pow(other_matching_bits, calc_value);
  if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
      FE_UNDERFLOW))
    {
      if (0 != fetestexcept(FE_OVERFLOW))
        GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
      if (0 != fetestexcept(FE_INVALID))
        GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
      if (0 != fetestexcept(FE_UNDERFLOW))
        GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
      return 0;
    }
  else
    return ret;
}

/**
 * Comparison function for two struct PeerInfo's
 * which have already had their matching bits to
 * some target calculated.
 *
 * @param p1 a pointer pointer to a struct PeerInfo
 * @param p2 a pointer pointer to a struct PeerInfo
 *
 * @return 0 if equidistant to target,
 *        -1 if p1 is closer,
 *         1 if p2 is closer
 */
static int
compare_peers (const void *p1, const void *p2)
{
  struct PeerInfo **first = (struct PeerInfo **)p1;
  struct PeerInfo **second = (struct PeerInfo **)p2;

  if ((*first)->matching_bits > (*second)->matching_bits)
    return -1;
  if ((*first)->matching_bits < (*second)->matching_bits)
    return 1;
  else
    return 0;
}


/**
 * Select a peer from the routing table that would be a good routing
 * destination for sending a message for "target".  The resulting peer
 * must not be in the set of blocked peers.<p>
 *
 * Note that we should not ALWAYS select the closest peer to the
 * target, peers further away from the target should be chosen with
 * exponentially declining probability.
 *
 * @param target the key we are selecting a peer to route to
 * @param bloom a bloomfilter containing entries this request has seen already
 *
 * @return Peer to route to, or NULL on error
 */
static struct PeerInfo *
select_peer (const GNUNET_HashCode * target,
             struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
{
  unsigned int bc;
  unsigned int i;
  unsigned int count;
  unsigned int offset;
  unsigned int my_matching_bits;
  int closest_bucket;
  struct PeerInfo *pos;
  struct PeerInfo *sorted_closest[bucket_size];
  unsigned long long temp_converge_distance;
  unsigned long long total_distance;
  unsigned long long selected;
#if DEBUG_DHT > 1
  unsigned long long stats_total_distance;
  double sum;
#endif
  /* For kademlia */
  unsigned int distance;
  unsigned int largest_distance;
  struct PeerInfo *chosen;

  my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);

  total_distance = 0;
  if (strict_kademlia == GNUNET_YES)
    {
      largest_distance = 0;
      chosen = NULL;
      for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
        {
          pos = k_buckets[bc].head;
          count = 0;
          while ((pos != NULL) && (count < bucket_size))
            {
              /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
              if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
                {
                  distance = inverse_distance (target, &pos->id.hashPubKey);
                  if (distance > largest_distance)
                    {
                      chosen = pos;
                      largest_distance = distance;
                    }
                }
              count++;
              pos = pos->next;
            }
        }

      if ((largest_distance > 0) && (chosen != NULL))
        {
          GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
          return chosen;
        }
      else
        {
          return NULL;
        }
    }

  /* GNUnet-style */
  total_distance = 0;
  /* Three steps: order peers in closest bucket (most matching bits).
   * Then go over all LOWER buckets (matching same bits we do)
   * Then go over all HIGHER buckets (matching less then we do)
   */

  closest_bucket = find_current_bucket(target);
  GNUNET_assert(closest_bucket >= lowest_bucket);
  pos = k_buckets[closest_bucket].head;
  count = 0;
  offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
  memset(sorted_closest, 0, sizeof(sorted_closest));
  /* Put any peers in the closest bucket in the sorting array */
  while ((pos != NULL) && (count < bucket_size))
    {
      if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
        {
          count++;
          pos = pos->next;
          continue; /* Ignore bloomfiltered peers */
        }
      pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
      sorted_closest[offset] = pos;
      pos = pos->next;
      offset++;
      count++;
    }

  /* Sort the peers in descending order */
  qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);

  /* Put the sorted closest peers into the possible bins first, in case of overflow. */
  for (i = 0; i < offset; i++)
    {
      temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
      if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
        break; /* Ignore bloomfiltered peers */
      if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
        total_distance += temp_converge_distance;
      else
        break; /* overflow case */
    }

  /* Now handle peers in lower buckets (matches same # of bits as target) */
  for (bc = lowest_bucket; bc < closest_bucket; bc++)
    {
      pos = k_buckets[bc].head;
      count = 0;
      while ((pos != NULL) && (count < bucket_size))
        {
          if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
            {
              count++;
              pos = pos->next;
              continue; /* Ignore bloomfiltered peers */
            }
          temp_converge_distance = converge_distance(target, pos, hops);
          if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
            total_distance += temp_converge_distance;
          else
            break; /* overflow case */
          pos = pos->next;
          count++;
        }
    }

  /* Now handle all the further away peers */
  for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
    {
      pos = k_buckets[bc].head;
      count = 0;
      while ((pos != NULL) && (count < bucket_size))
        {
          if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
            {
              count++;
              pos = pos->next;
              continue; /* Ignore bloomfiltered peers */
            }
          temp_converge_distance = converge_distance(target, pos, hops);
          if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
            total_distance += temp_converge_distance;
          else
            break; /* overflow case */
          pos = pos->next;
          count++;
        }
    }

  if (total_distance == 0) /* No peers to select from! */
    {
      increment_stats("# select_peer, total_distance == 0");
      return NULL;
    }

#if DEBUG_DHT_ROUTING > 1
  sum = 0.0;
  /* PRINT STATS */
  /* Put the sorted closest peers into the possible bins first, in case of overflow. */
  stats_total_distance = 0;
  for (i = 0; i < offset; i++)
    {
      if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
        break; /* Ignore bloomfiltered peers */
      temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
      if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
        stats_total_distance += temp_converge_distance;
      else
        break; /* overflow case */
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n", GNUNET_CRYPTO_hash_matching_bits(&sorted_closest[i]->id.hashPubKey, target), GNUNET_CRYPTO_hash_matching_bits(&sorted_closest[i]->id.hashPubKey, &my_identity.hashPubKey), (temp_converge_distance / (double)total_distance) * 100, temp_converge_distance);
    }

  /* Now handle peers in lower buckets (matches same # of bits as target) */
  for (bc = lowest_bucket; bc < closest_bucket; bc++)
    {
      pos = k_buckets[bc].head;
      count = 0;
      while ((pos != NULL) && (count < bucket_size))
        {
          if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
            {
              count++;
              pos = pos->next;
              continue; /* Ignore bloomfiltered peers */
            }
          temp_converge_distance = converge_distance(target, pos, hops);
          if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
            stats_total_distance += temp_converge_distance;
          else
            break; /* overflow case */
          GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n", GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target), GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey), (temp_converge_distance / (double)total_distance) * 100, temp_converge_distance);
          pos = pos->next;
          count++;
        }
    }

  /* Now handle all the further away peers */
  for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
    {
      pos = k_buckets[bc].head;
      count = 0;
      while ((pos != NULL) && (count < bucket_size))
        {
          if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
            {
              count++;
              pos = pos->next;
              continue; /* Ignore bloomfiltered peers */
            }
          temp_converge_distance = converge_distance(target, pos, hops);
          if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
            stats_total_distance += temp_converge_distance;
          else
            break; /* overflow case */
          GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n", GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target), GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey),  (temp_converge_distance / (double)total_distance) * 100, temp_converge_distance);
          pos = pos->next;
          count++;
        }
    }
  /* END PRINT STATS */
#endif

  /* Now actually choose a peer */
  selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);

  /* Put the sorted closest peers into the possible bins first, in case of overflow. */
  for (i = 0; i < offset; i++)
    {
      if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
        break; /* Ignore bloomfiltered peers */
      temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
      if (temp_converge_distance >= selected)
        return sorted_closest[i];
      else
        selected -= temp_converge_distance;
    }

  /* Now handle peers in lower buckets (matches same # of bits as target) */
  for (bc = lowest_bucket; bc < closest_bucket; bc++)
    {
      pos = k_buckets[bc].head;
      count = 0;
      while ((pos != NULL) && (count < bucket_size))
        {
          if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
            {
              count++;
              pos = pos->next;
              continue; /* Ignore bloomfiltered peers */
            }
          temp_converge_distance = converge_distance(target, pos, hops);
          if (temp_converge_distance >= selected)
            return pos;
          else
            selected -= temp_converge_distance;
          pos = pos->next;
          count++;
        }
    }

  /* Now handle all the further away peers */
  for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
    {
      pos = k_buckets[bc].head;
      count = 0;
      while ((pos != NULL) && (count < bucket_size))
        {
          if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
            {
              count++;
              pos = pos->next;
              continue; /* Ignore bloomfiltered peers */
            }
          temp_converge_distance = converge_distance(target, pos, hops);
          if (temp_converge_distance >= selected)
            return pos;
          else
            selected -= temp_converge_distance;
          pos = pos->next;
          count++;
        }
    }

  increment_stats("# failed to select peer");
  return NULL;
}


/**
 * Task used to remove recent entries, either
 * after timeout, when full, or on shutdown.
 *
 * @param cls the entry to remove
 * @param tc context, reason, etc.
 */
static void
remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct RecentRequest *req = cls;
  static GNUNET_HashCode hash;

  GNUNET_assert(req != NULL);
  hash_from_uid(req->uid, &hash);
  GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
  GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
  GNUNET_CONTAINER_bloomfilter_free(req->bloom);
  GNUNET_free(req);

  if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
  {
    GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
    GNUNET_CONTAINER_heap_destroy(recent.minHeap);
  }
}


/**
 * Task used to remove forwarding entries, either
 * after timeout, when full, or on shutdown.
 *
 * @param cls the entry to remove
 * @param tc context, reason, etc.
 */
static void
remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct DHTRouteSource *source_info = cls;
  struct DHTQueryRecord *record;
  source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
  record = source_info->record;
  GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);

  if (record->head == NULL) /* No more entries in DLL */
    {
      GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
      GNUNET_free(record);
    }
  if (source_info->find_peers_responded != NULL)
    GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
  GNUNET_free(source_info);
}

/**
 * Remember this routing request so that if a reply is
 * received we can either forward it to the correct peer
 * or return the result locally.
 *
 * @param cls DHT service closure
 * @param msg_ctx Context of the route request
 *
 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
 */
static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
{
  struct DHTQueryRecord *record;
  struct DHTRouteSource *source_info;
  struct DHTRouteSource *pos;
  struct GNUNET_TIME_Absolute now;
  unsigned int current_size;

  current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
  while (current_size >= MAX_OUTSTANDING_FORWARDS)
    {
      source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
      GNUNET_assert(source_info != NULL);
      record = source_info->record;
      GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
      if (record->head == NULL) /* No more entries in DLL */
        {
          GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
          GNUNET_free(record);
        }
      GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
      if (source_info->find_peers_responded != NULL)
        GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
      GNUNET_free(source_info);
      current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
    }
  now = GNUNET_TIME_absolute_get();
  record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
  if (record != NULL) /* Already know this request! */
    {
      pos = record->head;
      while (pos != NULL)
        {
          if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
            break; /* Already have this peer in reply list! */
          pos = pos->next;
        }
      if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
        {
          GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
          return GNUNET_NO;
        }
    }
  else
    {
      record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
      GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
      memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
    }

  source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
  source_info->record = record;
  source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
  source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
  memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
  GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
  if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
    {
      source_info->client = msg_ctx->client;
      now = GNUNET_TIME_absolute_get_forever();
    }
  source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
#if DEBUG_DHT > 1
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
                  "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
#endif
  return GNUNET_YES;
}


/**
 * Main function that handles whether or not to route a message to other
 * peers.
 *
 * @param cls closure for dht service (NULL)
 * @param msg the message to be routed
 * @param message_context the context containing all pertinent information about the message
 *
 * @return the number of peers the message was routed to,
 *         GNUNET_SYSERR on failure
 */
static int route_message(void *cls,
                         const struct GNUNET_MessageHeader *msg,
                         struct DHT_MessageContext *message_context)
{
  int i;
  int global_closest;
  struct PeerInfo *selected;
#if DEBUG_DHT_ROUTING > 1
  struct PeerInfo *nearest;
#endif
  unsigned int forward_count;
  struct RecentRequest *recent_req;
  GNUNET_HashCode unique_hash;
  char *stat_forward_count;
  char *temp_stat_str;
#if DEBUG_DHT_ROUTING
  int ret;
#endif

  if (malicious_dropper == GNUNET_YES)
    {
#if DEBUG_DHT_ROUTING
      if ((debug_routes_extended) && (dhtlog_handle != NULL))
        {
          dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
                                       message_context->hop_count, GNUNET_SYSERR,
                                       &my_identity, &message_context->key, message_context->peer,
                                       NULL);
        }
#endif
      if (message_context->bloom != NULL)
        GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
      return 0;
    }

  increment_stats(STAT_ROUTES);
  /* Semantics of this call means we find whether we are the closest peer out of those already
   * routed to on this messages path.
   */
  global_closest = am_closest_peer(&message_context->key, NULL);
  message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
  forward_count = get_forward_count(message_context->hop_count, message_context->replication);
  GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
  increment_stats(stat_forward_count);
  GNUNET_free(stat_forward_count);
  if (message_context->bloom == NULL)
    message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);

  if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
    forward_count = 0;

  /**
   * NOTICE:  In Kademlia, a find peer request goes no further if the peer doesn't return
   * any closer peers (which is being checked for below).  Since we are doing recursive
   * routing we have no choice but to stop forwarding in this case.  This means that at
   * any given step the request may NOT be forwarded to alpha peers (because routes will
   * stop and the parallel route will not be aware of it).  Of course, assuming that we
   * have fulfilled the Kademlia requirements for routing table fullness this will never
   * ever ever be a problem.
   *
   * However, is this fair?
   *
   * Since we use these requests to build our routing tables (and we build them in the
   * testing driver) we will ignore this restriction for FIND_PEER messages so that
   * routing tables still get constructed.
   */
  if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
    forward_count = 0;

#if DEBUG_DHT_ROUTING
  if (forward_count == 0)
    ret = GNUNET_SYSERR;
  else
    ret = GNUNET_NO;

  if ((debug_routes_extended) && (dhtlog_handle != NULL))
    {
      dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
                                   message_context->hop_count, ret,
                                   &my_identity, &message_context->key, message_context->peer,
                                   NULL);
    }
#endif

  switch (ntohs(msg->type))
    {
    case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
      cache_response (cls, message_context);
      if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
        forward_count = 0;
      break;
    case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
      increment_stats(STAT_PUTS);
      message_context->closest = global_closest;
      handle_dht_put (cls, msg, message_context);
      break;
    case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
      increment_stats(STAT_FIND_PEER);
      if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
      {
        cache_response (cls, message_context);
        if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
          handle_dht_find_peer (cls, msg, message_context);
      }
#if DEBUG_DHT_ROUTING
      if (message_context->hop_count == 0) /* Locally initiated request */
        {
          if ((debug_routes) && (dhtlog_handle != NULL))
            {
              dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
              dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
                                           message_context->hop_count, GNUNET_NO, &my_identity,
                                           &message_context->key);
            }
        }
#endif
      break;
    default:
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
    }

  GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
  hash_from_uid (message_context->unique_id, &unique_hash);
  if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
  {
    recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
    GNUNET_assert(recent_req != NULL);
    if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
      increment_stats(STAT_DUPLICATE_UID);
    else
      {
        increment_stats(STAT_RECENT_SEEN);
        GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
      }
    }
  else
    {
      recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
      recent_req->uid = message_context->unique_id;
      memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
      recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
      recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
      recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
      GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
    }

  if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
    {
      recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
      GNUNET_assert(recent_req != NULL);
      GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
      GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
    }

  for (i = 0; i < forward_count; i++)
    {
      selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);

      if (selected != NULL)
        {
          if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
            GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
          else
            GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
          if (temp_stat_str != NULL)
            {
              increment_stats(temp_stat_str);
              GNUNET_free(temp_stat_str);
            }
          GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
#if DEBUG_DHT_ROUTING > 1
          nearest = find_closest_peer(&message_context->key);
          nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                      "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
                      "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&selected->id), nearest_buf, GNUNET_CRYPTO_hash_matching_bits(&nearest->id.hashPubKey, message_context->key), distance(&nearest->id.hashPubKey, message_context->key));
          GNUNET_free(nearest_buf);
#endif
#if DEBUG_DHT_ROUTING
          if ((debug_routes_extended) && (dhtlog_handle != NULL))
            {
              dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
                                           message_context->hop_count, GNUNET_NO,
                                           &my_identity, &message_context->key, message_context->peer,
                                           &selected->id);
            }
#endif
          forward_message(cls, msg, selected, message_context);
        }
    }

  if (message_context->bloom != NULL)
    {
      GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
      GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
    }

  return forward_count;
}

/**
 * Iterator for local get request results,
 *
 * @param cls closure for iterator, NULL
 * @param exp when does this value expire?
 * @param key the key this data is stored under
 * @param size the size of the data identified by key
 * @param data the actual data
 * @param type the type of the data
 *
 * @return GNUNET_OK to continue iteration, anything else
 * to stop iteration.
 */
static int
republish_content_iterator (void *cls,
                            struct GNUNET_TIME_Absolute exp,
                            const GNUNET_HashCode * key,
                            uint32_t size, const char *data, uint32_t type)
{

  struct DHT_MessageContext *new_msg_ctx;
  struct GNUNET_DHT_PutMessage *put_msg;
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
#endif
  new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));

  put_msg =
    GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
  put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
  put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
  put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
  put_msg->type = htons (type);
  memcpy (&put_msg[1], data, size);
  new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
  new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
  new_msg_ctx->msg_options = ntohl (0);
  new_msg_ctx->network_size = estimate_diameter();
  new_msg_ctx->peer = &my_identity;
  new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
  new_msg_ctx->hop_count = 0;
  new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
  new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
  increment_stats(STAT_PUT_START);
  route_message(cls, &put_msg->header, new_msg_ctx);

  GNUNET_free(new_msg_ctx);
  GNUNET_free (put_msg);
  return GNUNET_OK;
}

/**
 * Task used to republish data.
 *
 * @param cls closure (a struct RepublishContext)
 * @param tc runtime context for this task
 */
static void
republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct RepublishContext *put_context = cls;

  unsigned int results;

  if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
    {
      GNUNET_free(put_context);
      return;
    }

  GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
  results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
  if (results == 0) /* Data must have expired */
    GNUNET_free(put_context);
  else /* Reschedule task for next time period */
    GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);

}


/**
 * Iterator over hash map entries.
 *
 * @param cls client to search for in source routes
 * @param key current key code (ignored)
 * @param value value in the hash map, a DHTQueryRecord
 * @return GNUNET_YES if we should continue to
 *         iterate,
 *         GNUNET_NO if not.
 */
static int find_client_records (void *cls,
                                const GNUNET_HashCode * key, void *value)
{
  struct ClientList *client = cls;
  struct DHTQueryRecord *record = value;
  struct DHTRouteSource *pos;
  pos = record->head;
  while (pos != NULL)
    {
      if (pos->client == client)
        break;
      pos = pos->next;
    }
  if (pos != NULL)
    {
      GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
      GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
      if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
        GNUNET_SCHEDULER_cancel(sched, pos->delete_task);

      if (pos->find_peers_responded != NULL)
        GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
      GNUNET_free(pos);
    }
  if (record->head == NULL) /* No more entries in DLL */
    {
      GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
      GNUNET_free(record);
    }
  return GNUNET_YES;
}

/**
 * Functions with this signature are called whenever a client
 * is disconnected on the network level.
 *
 * @param cls closure (NULL for dht)
 * @param client identification of the client; NULL
 *        for the last call when the server is destroyed
 */
static void handle_client_disconnect (void *cls,
                                      struct GNUNET_SERVER_Client* client)
{
  struct ClientList *pos = client_list;
  struct ClientList *prev;
  struct ClientList *found;
  struct PendingMessage *reply;

  prev = NULL;
  found = NULL;
  while (pos != NULL)
    {
      if (pos->client_handle == client)
        {
          if (prev != NULL)
            prev->next = pos->next;
          else
            client_list = pos->next;
          found = pos;
          break;
        }
      prev = pos;
      pos = pos->next;
    }

  if (found != NULL)
    {
      while(NULL != (reply = found->pending_head))
        {
          GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
          GNUNET_free(reply);
        }
      GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
      GNUNET_free(found);
    }
}

/**
 * Find a client if it exists, add it otherwise.
 *
 * @param client the server handle to the client
 *
 * @return the client if found, a new client otherwise
 */
static struct ClientList *
find_active_client (struct GNUNET_SERVER_Client *client)
{
  struct ClientList *pos = client_list;
  struct ClientList *ret;

  while (pos != NULL)
    {
      if (pos->client_handle == client)
        return pos;
      pos = pos->next;
    }

  ret = GNUNET_malloc (sizeof (struct ClientList));
  ret->client_handle = client;
  ret->next = client_list;
  client_list = ret;

  return ret;
}

/**
 * Task to send a malicious put message across the network.
 *
 * @param cls closure for this task
 * @param tc the context under which the task is running
 */
static void
malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  static struct GNUNET_DHT_PutMessage put_message;
  static struct DHT_MessageContext message_context;
  static GNUNET_HashCode key;
  uint32_t random_key;

  if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
    return;

  put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
  put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
  put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
  put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
  memset(&message_context, 0, sizeof(struct DHT_MessageContext));
  message_context.client = NULL;
  random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
  GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
  memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
  message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
  message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
  message_context.msg_options = ntohl (0);
  message_context.network_size = estimate_diameter();
  message_context.peer = &my_identity;
  message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
  message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
#if DEBUG_DHT_ROUTING
  if (dhtlog_handle != NULL)
    dhtlog_handle->insert_dhtkey(NULL, &key);
#endif
  increment_stats(STAT_PUT_START);
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
  route_message(NULL, &put_message.header, &message_context);
  GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);

}

/**
 * Task to send a malicious put message across the network.
 *
 * @param cls closure for this task
 * @param tc the context under which the task is running
 */
static void
malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  static struct GNUNET_DHT_GetMessage get_message;
  struct DHT_MessageContext message_context;
  static GNUNET_HashCode key;
  uint32_t random_key;

  if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
    return;

  get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
  get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
  get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
  memset(&message_context, 0, sizeof(struct DHT_MessageContext));
  message_context.client = NULL;
  random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
  GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
  memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
  message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
  message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
  message_context.msg_options = ntohl (0);
  message_context.network_size = estimate_diameter();
  message_context.peer = &my_identity;
  message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
  message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
#if DEBUG_DHT_ROUTING
  if (dhtlog_handle != NULL)
    dhtlog_handle->insert_dhtkey(NULL, &key);
#endif
  increment_stats(STAT_GET_START);
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
  route_message (NULL, &get_message.header, &message_context);
  GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
}

/**
 * Iterator over hash map entries.
 *
 * @param cls closure
 * @param key current key code
 * @param value value in the hash map
 * @return GNUNET_YES if we should continue to
 *         iterate,
 *         GNUNET_NO if not.
 */
static int
add_known_to_bloom (void *cls,
                    const GNUNET_HashCode * key,
                    void *value)
{
  struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
  GNUNET_CONTAINER_bloomfilter_add (bloom, key);
  return GNUNET_YES;
}

/**
 * Task to send a find peer message for our own peer identifier
 * so that we can find the closest peers in the network to ourselves
 * and attempt to connect to them.
 *
 * @param cls closure for this task
 * @param tc the context under which the task is running
 */
static void
send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
  struct DHT_MessageContext message_context;
  int ret;
  struct GNUNET_TIME_Relative next_send_time;
  struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
#if COUNT_INTERVAL
  struct GNUNET_TIME_Relative time_diff;
  struct GNUNET_TIME_Absolute end;
  double multiplier;
  double count_per_interval;
#endif
  if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
    return;

  if ((newly_found_peers > bucket_size) && (GNUNET_YES == do_find_peer)) /* If we are finding peers already, no need to send out our request right now! */
    {
      GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
      GNUNET_SCHEDULER_add_delayed (sched,
                                    GNUNET_TIME_UNIT_MINUTES,
                                    &send_find_peer_message, NULL);
      newly_found_peers = 0;
      return;
    }
    
  increment_stats(STAT_FIND_PEER_START);
#if COUNT_INTERVAL
  end = GNUNET_TIME_absolute_get();
  time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);

  if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
    {
      multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
      count_per_interval = find_peer_context.count / multiplier;
    }
  else
    {
      multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
      count_per_interval = find_peer_context.count * multiplier;
    }
#endif

#if FIND_PEER_WITH_HELLO
  find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
  find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
  memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
#else
  find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
  find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
#endif
  find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
  temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
  GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
  GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
  memset(&message_context, 0, sizeof(struct DHT_MessageContext));
  memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
  message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
  message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
  message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
  message_context.network_size = estimate_diameter();
  message_context.peer = &my_identity;
  message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
  message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;

  ret = route_message(NULL, &find_peer_msg->header, &message_context);
  GNUNET_free(find_peer_msg);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
              "FIND PEER", ret);
  if (newly_found_peers < bucket_size)
    {
      next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
                              GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
                                                       DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
    }
  else
    {
      next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
                             GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
                                                      DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
    }

  GNUNET_assert (next_send_time.value != 0);
  find_peer_context.count = 0;
  newly_found_peers = 0;
  find_peer_context.start = GNUNET_TIME_absolute_get();
  if (GNUNET_YES == do_find_peer)
  {
    GNUNET_SCHEDULER_add_delayed (sched,
                                  next_send_time,
       	                          &send_find_peer_message, NULL);
  }
}

/**
 * Handler for any generic DHT messages, calls the appropriate handler
 * depending on message type, sends confirmation if responses aren't otherwise
 * expected.
 *
 * @param cls closure for the service
 * @param client the client we received this message from
 * @param message the actual message received
 */
static void
handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
                                const struct GNUNET_MessageHeader *message)
{
  const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
  const struct GNUNET_MessageHeader *enc_msg;
  struct DHT_MessageContext message_context;

  enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
              my_short_id, 
	      "DHT",
	      "GENERIC",
	      ntohs (message->type), 
	      GNUNET_h2s (&dht_msg->key),
              GNUNET_ntohll (dht_msg->unique_id));
#endif
#if DEBUG_DHT_ROUTING
  if (dhtlog_handle != NULL)
    dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
#endif
  memset(&message_context, 0, sizeof(struct DHT_MessageContext));
  message_context.client = find_active_client (client);
  memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
  message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
  message_context.replication = ntohl (dht_msg->desired_replication_level);
  message_context.msg_options = ntohl (dht_msg->options);
  message_context.network_size = estimate_diameter();
  message_context.peer = &my_identity;
  message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
  message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
  if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
    increment_stats(STAT_GET_START);
  else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
    increment_stats(STAT_PUT_START);
  else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
    increment_stats(STAT_FIND_PEER_START);

  route_message(cls, enc_msg, &message_context);

  GNUNET_SERVER_receive_done (client, GNUNET_OK);

}

/**
 * Handler for any locally received DHT control messages,
 * sets malicious flags mostly for now.
 *
 * @param cls closure for the service
 * @param client the client we received this message from
 * @param message the actual message received
 *
 */
static void
handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
                            const struct GNUNET_MessageHeader *message)
{
  const struct GNUNET_DHT_ControlMessage *dht_control_msg =
      (const struct GNUNET_DHT_ControlMessage *) message;
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
              "CONTROL", ntohs(dht_control_msg->command));
#endif

  switch (ntohs(dht_control_msg->command))
  {
  case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
    GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
    break;
  case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
    if (ntohs(dht_control_msg->variable) > 0)
      malicious_get_frequency = ntohs(dht_control_msg->variable);
    if (malicious_get_frequency == 0)
      malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
    if (malicious_getter != GNUNET_YES)
      GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
    malicious_getter = GNUNET_YES;
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
	       "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
    break;
  case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
    if (ntohs(dht_control_msg->variable) > 0)
      malicious_put_frequency = ntohs(dht_control_msg->variable);
    if (malicious_put_frequency == 0)
      malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
    if (malicious_putter != GNUNET_YES)
      GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
    malicious_putter = GNUNET_YES;
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
	       "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
    break;
  case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
#if DEBUG_DHT_ROUTING
    if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
      dhtlog_handle->set_malicious(&my_identity);
#endif
    malicious_dropper = GNUNET_YES;
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
	       "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
    break;
  default:
    GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
	       "%s:%s Unknown control command type `%d'!\n", 
	       my_short_id, "DHT",
	       ntohs(dht_control_msg->command));
    break;
  }

  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}

/**
 * Handler for any generic DHT stop messages, calls the appropriate handler
 * depending on message type (if processed locally)
 *
 * @param cls closure for the service
 * @param client the client we received this message from
 * @param message the actual message received
 *
 */
static void
handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
                            const struct GNUNET_MessageHeader *message)
{

  const struct GNUNET_DHT_StopMessage *dht_stop_msg =
    (const struct GNUNET_DHT_StopMessage *) message;
  struct DHTQueryRecord *record;
  struct DHTRouteSource *pos;
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
              "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
#endif
  record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
  if (record != NULL)
    {
      pos = record->head;

      while (pos != NULL)
        {
          if ((pos->client != NULL) && (pos->client->client_handle == client))
            {
              GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
              GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
            }
          pos = pos->next;
        }
    }

  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}


/**
 * Core handler for p2p route requests.
 */
static int
handle_dht_p2p_route_request (void *cls,
			      const struct GNUNET_PeerIdentity *peer,
			      const struct GNUNET_MessageHeader *message,
			      struct GNUNET_TIME_Relative latency, uint32_t distance)
{
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
#endif
  struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
  struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
  struct DHT_MessageContext *message_context;

  if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
  {
    GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
    increment_stats("# route requests dropped due to high load");
    decrease_max_send_delay(get_max_send_delay());
    return GNUNET_YES;
  }

  if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
    {
#if DEBUG_PING
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
#endif
      return GNUNET_YES;
    }

  if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
    {
      GNUNET_break_op(0);
      return GNUNET_YES;
    }
  message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
  message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
  GNUNET_assert(message_context->bloom != NULL);
  message_context->hop_count = ntohl(incoming->hop_count);
  memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
  message_context->replication = ntohl(incoming->desired_replication_level);
  message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
  message_context->msg_options = ntohl(incoming->options);
  message_context->network_size = ntohl(incoming->network_size);
  message_context->peer = peer;
  message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
  message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
  route_message(cls, enc_msg, message_context);
  GNUNET_free(message_context);
  return GNUNET_YES;
}


/**
 * Core handler for p2p route results.
 */
static int
handle_dht_p2p_route_result (void *cls,
			     const struct GNUNET_PeerIdentity *peer,
			     const struct GNUNET_MessageHeader *message,
			     struct GNUNET_TIME_Relative latency, uint32_t distance)
{
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
#endif
  struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
  struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
  struct DHT_MessageContext message_context;

  if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
    {
      GNUNET_break_op(0);
      return GNUNET_YES;
    }

  memset(&message_context, 0, sizeof(struct DHT_MessageContext));
  // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
  message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
  GNUNET_assert(message_context.bloom != NULL);
  memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
  message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
  message_context.msg_options = ntohl(incoming->options);
  message_context.hop_count = ntohl(incoming->hop_count);
  message_context.peer = peer;
  message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
  message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
  route_result_message(cls, enc_msg, &message_context);
  return GNUNET_YES;
}


/**
 * Receive the HELLO from transport service,
 * free current and replace if necessary.
 *
 * @param cls NULL
 * @param message HELLO message of peer
 */
static void
process_hello (void *cls, const struct GNUNET_MessageHeader *message)
{
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Received our `%s' from transport service\n",
              "HELLO");
#endif

  GNUNET_assert (message != NULL);
  GNUNET_free_non_null(my_hello);
  my_hello = GNUNET_malloc(ntohs(message->size));
  memcpy(my_hello, message, ntohs(message->size));
}


/**
 * Task run during shutdown.
 *
 * @param cls unused
 * @param tc unused
 */
static void
shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  int bucket_count;
  struct PeerInfo *pos;
  if (transport_handle != NULL)
  {
    GNUNET_free_non_null(my_hello);
    GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
    GNUNET_TRANSPORT_disconnect(transport_handle);
  }

  for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
    {
      while (k_buckets[bucket_count].head != NULL)
        {
          pos = k_buckets[bucket_count].head;
#if DEBUG_DHT
          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                      "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
#endif
          delete_peer(pos, bucket_count);
        }
    }
  if (coreAPI != NULL)
    {
#if DEBUG_DHT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "%s:%s Disconnecting core!\n", my_short_id, "DHT");
#endif
      GNUNET_CORE_disconnect (coreAPI);
    }
  if (datacache != NULL)
    {
#if DEBUG_DHT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "%s:%s Destroying datacache!\n", my_short_id, "DHT");
#endif
      GNUNET_DATACACHE_destroy (datacache);
    }

  if (stats != NULL)
    {
      GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
    }

  if (dhtlog_handle != NULL)
    GNUNET_DHTLOG_disconnect(dhtlog_handle);

  GNUNET_free_non_null(my_short_id);
}


/**
 * To be called on core init/fail.
 *
 * @param cls service closure
 * @param server handle to the server for this service
 * @param identity the public identity of this peer
 * @param publicKey the public key of this peer
 */
void
core_init (void *cls,
           struct GNUNET_CORE_Handle *server,
           const struct GNUNET_PeerIdentity *identity,
           const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
{

  if (server == NULL)
    {
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "%s: Connection to core FAILED!\n", "dht",
              GNUNET_i2s (identity));
#endif
      GNUNET_SCHEDULER_cancel (sched, cleanup_task);
      GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
      return;
    }
#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "%s: Core connection initialized, I am peer: %s\n", "dht",
              GNUNET_i2s (identity));
#endif

  /* Copy our identity so we can use it */
  memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
  if (my_short_id != NULL)
    GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
  my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
  /* Set the server to local variable */
  coreAPI = server;

  if (dhtlog_handle != NULL)
    dhtlog_handle->insert_node (NULL, &my_identity);
}


static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
  {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
  {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
  {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
  {NULL, NULL, 0, 0}
};


static struct GNUNET_CORE_MessageHandler core_handlers[] = {
  {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
  {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
  {NULL, 0, 0}
};

/**
 * Method called whenever a peer connects.
 *
 * @param cls closure
 * @param peer peer identity this notification is about
 * @param latency reported latency of the connection with peer
 * @param distance reported distance (DV) to peer
 */
void handle_core_connect (void *cls,
                          const struct GNUNET_PeerIdentity * peer,
                          struct GNUNET_TIME_Relative latency,
                          uint32_t distance)
{
  struct PeerInfo *ret;

#if DEBUG_DHT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
#endif

  if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received %s message for peer %s, but already have peer in RT!", my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s(peer));
      return;
    }

  if (datacache != NULL)
    GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
  ret = try_add_peer(peer,
                     find_current_bucket(&peer->hashPubKey),
                     latency,
                     distance);
  if (ret != NULL)
    {
      newly_found_peers++;
      GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
    }
#if DEBUG_DHT
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
#endif
}

/**
 * Method called whenever a peer disconnects.
 *
 * @param cls closure
 * @param peer peer identity this notification is about
 */
void handle_core_disconnect (void *cls,
                             const struct
                             GNUNET_PeerIdentity * peer)
{
  struct PeerInfo *to_remove;
  int current_bucket;

  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s: Received peer disconnect message for peer `%s' from %s\n", my_short_id, "DHT", GNUNET_i2s(peer), "CORE");

  if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
    {
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s: do not have peer `%s' in RT, can't disconnect!\n", my_short_id, "DHT", GNUNET_i2s(peer));
      return;
    }
  increment_stats(STAT_DISCONNECTS);
  GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
  to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
  GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
  current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
  delete_peer(to_remove, current_bucket);
}

/**
 * Process dht requests.
 *
 * @param cls closure
 * @param scheduler scheduler to use
 * @param server the initialized server
 * @param c configuration to use
 */
static void
run (void *cls,
     struct GNUNET_SCHEDULER_Handle *scheduler,
     struct GNUNET_SERVER_Handle *server,
     const struct GNUNET_CONFIGURATION_Handle *c)
{
  struct GNUNET_TIME_Relative next_send_time;
  unsigned long long temp_config_num;
  char *converge_modifier_buf;
  sched = scheduler;
  cfg = c;
  datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
  GNUNET_SERVER_add_handlers (server, plugin_handlers);
  GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
  coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
                                 cfg,   /* Main configuration */
                                 GNUNET_TIME_UNIT_FOREVER_REL,
                                 NULL,  /* Closure passed to DHT functions */
                                 &core_init,    /* Call core_init once connected */
                                 &handle_core_connect,  /* Handle connects */
                                 &handle_core_disconnect,  /* remove peers on disconnects */
                                 NULL,  /* Do we care about "status" updates? */
                                 NULL,  /* Don't want notified about all incoming messages */
                                 GNUNET_NO,     /* For header only inbound notification */
                                 NULL,  /* Don't want notified about all outbound messages */
                                 GNUNET_NO,     /* For header only outbound notification */
                                 core_handlers);        /* Register these handlers */

  if (coreAPI == NULL)
    return;
  transport_handle = GNUNET_TRANSPORT_connect(sched, cfg, 
					      NULL, NULL, NULL, NULL, NULL);
  if (transport_handle != NULL)
    GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
  else
    GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");

  lowest_bucket = MAX_BUCKETS - 1;
  forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
  forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
  all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
  recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
  GNUNET_assert(all_known_peers != NULL);
  if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
    {
      debug_routes = GNUNET_YES;
    }

  if (GNUNET_YES ==
      GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
                                           "strict_kademlia"))
    {
      strict_kademlia = GNUNET_YES;
    }

  if (GNUNET_YES ==
      GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
                                           "stop_on_closest"))
    {
      stop_on_closest = GNUNET_YES;
    }

  if (GNUNET_YES ==
      GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
                                           "stop_found"))
    {
      stop_on_found = GNUNET_YES;
    }

  if (GNUNET_YES ==
      GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
                                           "malicious_getter"))
    {
      malicious_getter = GNUNET_YES;
      if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
                                            "MALICIOUS_GET_FREQUENCY",
                                            &malicious_get_frequency))
        malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
    }

  if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
                                        "MAX_HOPS",
                                        &max_hops))
    {
      max_hops = DEFAULT_MAX_HOPS;
    }

  if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
                                                          "USE_MAX_HOPS"))
    {
      use_max_hops = GNUNET_YES;
    }

  if (GNUNET_YES ==
      GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
                                           "malicious_putter"))
    {
      malicious_putter = GNUNET_YES;
      if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
                                            "MALICIOUS_PUT_FREQUENCY",
                                            &malicious_put_frequency))
        malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
    }

  dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
  if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
    {
      dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
    }

  if (GNUNET_YES ==
          GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
                                               "malicious_dropper"))
    {
      malicious_dropper = GNUNET_YES;
    }

  if (GNUNET_YES ==
        GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
                                             "republish"))
    do_republish = GNUNET_NO;

  if (GNUNET_NO ==
        GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
                                             "do_find_peer"))
    {
      do_find_peer = GNUNET_NO;
    }
  else
    do_find_peer = GNUNET_YES;

  if (GNUNET_YES ==
        GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
                                             "use_real_distance"))
    use_real_distance = GNUNET_YES;

  if (GNUNET_YES ==
      GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
                                           "mysql_logging_extended"))
    {
      debug_routes = GNUNET_YES;
      debug_routes_extended = GNUNET_YES;
    }

#if DEBUG_DHT_ROUTING
  if (GNUNET_YES == debug_routes)
    {
      dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
      if (dhtlog_handle == NULL)
        {
          GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                      "Could not connect to mysql logging server, logging will not happen!");
        }
    }
#endif

  converge_option = DHT_CONVERGE_SQUARE;
  if (GNUNET_YES ==
      GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
                                           "converge_linear"))
    {
      converge_option = DHT_CONVERGE_LINEAR;
    }
  else if (GNUNET_YES ==
        GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
                                             "converge_exponential"))
    {
      converge_option = DHT_CONVERGE_EXPONENTIAL;
    }
  else if (GNUNET_YES ==
        GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
                                             "converge_random"))
    {
      converge_option = DHT_CONVERGE_RANDOM;
    }

  if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
    {
      if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
        {
          GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
          converge_modifier = 0.0;
        }
      GNUNET_free(converge_modifier_buf);
    }

  stats = GNUNET_STATISTICS_create(sched, "dht", cfg);

  if (stats != NULL)
    {
      GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
      GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
    }
  /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
  recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
  recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
  if (GNUNET_YES == do_find_peer)
  {
    next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
                           GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
                                                    (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
    find_peer_context.start = GNUNET_TIME_absolute_get();
    GNUNET_SCHEDULER_add_delayed (sched,
                                  next_send_time,
                                  &send_find_peer_message, &find_peer_context);
  }

  /* Scheduled the task to clean up when shutdown is called */
  cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
                                               GNUNET_TIME_UNIT_FOREVER_REL,
                                               &shutdown_task, NULL);
}

/**
 * The main function for the dht 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)
{
  return (GNUNET_OK ==
          GNUNET_SERVICE_run (argc,
                              argv,
                              "dht",
                              GNUNET_SERVICE_OPTION_NONE,
                              &run, NULL)) ? 0 : 1;
}