summaryrefslogtreecommitdiff
path: root/src/transport/gnunet-service-transport.c
blob: e2168b9709aa87f8ad381ae3bfa4a1eb6fda3a49 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
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
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
/*
     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 transport/gnunet-service-transport.c
 * @brief low-level P2P messaging
 * @author Christian Grothoff
 *
 */
#include "platform.h"
#include "gnunet_client_lib.h"
#include "gnunet_container_lib.h"
#include "gnunet_constants.h"
#include "gnunet_getopt_lib.h"
#include "gnunet_hello_lib.h"
#include "gnunet_os_lib.h"
#include "gnunet_peerinfo_service.h"
#include "gnunet_plugin_lib.h"
#include "gnunet_protocols.h"
#include "gnunet_service_lib.h"
#include "gnunet_signatures.h"
#include "gnunet_transport_plugin.h"
#include "transport.h"

#define DEBUG_BLACKLIST GNUNET_YES

#define DEBUG_PING_PONG GNUNET_YES

#define DEBUG_TRANSPORT_HELLO GNUNET_YES

/**
 * Should we do some additional checks (to validate behavior
 * of clients)?
 */
#define EXTRA_CHECKS GNUNET_YES

/**
 * How many messages can we have pending for a given client process
 * before we start to drop incoming messages?  We typically should
 * have only one client and so this would be the primary buffer for
  * messages, so the number should be chosen rather generously.
 *
 * The expectation here is that most of the time the queue is large
 * enough so that a drop is virtually never required.  Note that
 * this value must be about as large as 'TOTAL_MSGS' in the
 * 'test_transport_api_reliability.c', otherwise that testcase may
 * fail.
 */
#define MAX_PENDING (128 * 1024)

/**
 * Size of the per-transport blacklist hash maps.
 */
#define TRANSPORT_BLACKLIST_HT_SIZE 16

/**
 * How often should we try to reconnect to a peer using a particular
 * transport plugin before giving up?  Note that the plugin may be
 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
 */
#define MAX_CONNECT_RETRY 3

/**
 * Limit on the number of ready-to-run tasks when validating
 * HELLOs.  If more tasks are ready to run, we will drop
 * HELLOs instead of validating them.
 */
#define MAX_HELLO_LOAD 4

/**
 * How often must a peer violate bandwidth quotas before we start
 * to simply drop its messages?
 */
#define QUOTA_VIOLATION_DROP_THRESHOLD 10

/**
 * How long until a HELLO verification attempt should time out?
 * Must be rather small, otherwise a partially successful HELLO
 * validation (some addresses working) might not be available
 * before a client's request for a connection fails for good.
 * Besides, if a single request to an address takes a long time,
 * then the peer is unlikely worthwhile anyway.
 */
#define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)

/**
 * How long is a PONG signature valid?  We'll recycle a signature until
 * 1/4 of this time is remaining.  PONGs should expire so that if our
 * external addresses change an adversary cannot replay them indefinitely.
 * OTOH, we don't want to spend too much time generating PONG signatures,
 * so they must have some lifetime to reduce our CPU usage.
 */
#define PONG_SIGNATURE_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)

/**
 * Priority to use for PONG messages.
 */
#define TRANSPORT_PONG_PRIORITY 4

/**
 * How often do we re-add (cheaper) plugins to our list of plugins
 * to try for a given connected peer?
 */
#define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)

/**
 * After how long do we expire an address in a HELLO that we just
 * validated?  This value is also used for our own addresses when we
 * create a HELLO.
 */
#define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)


/**
 * How long before an existing address expires should we again try to
 * validate it?  Must be (significantly) smaller than
 * HELLO_ADDRESS_EXPIRATION.
 */
#define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)

/**
 * Maximum frequency for re-evaluating latencies for all transport addresses.
 */
#define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)

/**
 * Maximum frequency for re-evaluating latencies for connected addresses.
 */
#define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)


/**
 * List of addresses of other peers
 */
struct ForeignAddressList
{
  /**
   * This is a linked list.
   */
  struct ForeignAddressList *next;

  /**
   * Which ready list does this entry belong to.
   */
  struct ReadyList *ready_list;

  /**
   * How long until we auto-expire this address (unless it is
   * re-confirmed by the transport)?
   */
  struct GNUNET_TIME_Absolute expires;

  /**
   * Task used to re-validate addresses, updates latencies and
   * verifies liveness.
   */
  GNUNET_SCHEDULER_TaskIdentifier revalidate_task;

  /**
   * The address.
   */
  const void *addr;

  /**
   * Session (or NULL if no valid session currently exists or if the
   * plugin does not use sessions).
   */
  struct Session *session;

  /**
   * What was the last latency observed for this address, plugin and peer?
   */
  struct GNUNET_TIME_Relative latency;

  /**
   * If we did not successfully transmit a message to the given peer
   * via this connection during the specified time, we should consider
   * the connection to be dead.  This is used in the case that a TCP
   * transport simply stalls writing to the stream but does not
   * formerly get a signal that the other peer died.
   */
  struct GNUNET_TIME_Absolute timeout;

  /**
   * How often have we tried to connect using this plugin?  Used to
   * discriminate against addresses that do not work well.
   * FIXME: not yet used, but should be!
   */
  unsigned int connect_attempts;

  /**
   * DV distance to this peer (1 if no DV is used).
   * FIXME: need to set this from transport plugins!
   */
  uint32_t distance;

  /**
   * Length of addr.
   */
  uint16_t addrlen;

  /**
   * Have we ever estimated the latency of this address?  Used to
   * ensure that the first time we add an address, we immediately
   * probe its latency.
   */
  int8_t estimated;

  /**
   * Are we currently connected via this address?  The first time we
   * successfully transmit or receive data to a peer via a particular
   * address, we set this to GNUNET_YES.  If we later get an error
   * (disconnect notification, transmission failure, timeout), we set
   * it back to GNUNET_NO.
   */
  int8_t connected;

  /**
   * Is this plugin currently busy transmitting to the specific target?
   * GNUNET_NO if not (initial, default state is GNUNET_NO).   Internal
   * messages do not count as 'in transmit'.
   */
  int8_t in_transmit;

  /**
   * Has this address been validated yet?
   */
  int8_t validated;

};


/**
 * Entry in linked list of network addresses for ourselves.  Also
 * includes a cached signature for 'struct TransportPongMessage's.
 */
struct OwnAddressList
{
  /**
   * This is a linked list.
   */
  struct OwnAddressList *next;

  /**
   * How long until we actually auto-expire this address (unless it is
   * re-confirmed by the transport)?
   */
  struct GNUNET_TIME_Absolute expires;

  /**
   * How long until the current signature expires? (ZERO if the
   * signature was never created).
   */
  struct GNUNET_TIME_Absolute pong_sig_expires;

  /**
   * Signature for a 'struct TransportPongMessage' for this address.
   */
  struct GNUNET_CRYPTO_RsaSignature pong_signature;

  /**
   * Length of addr.
   */
  uint32_t addrlen;

};


/**
 * Entry in linked list of all of our plugins.
 */
struct TransportPlugin
{

  /**
   * This is a linked list.
   */
  struct TransportPlugin *next;

  /**
   * API of the transport as returned by the plugin's
   * initialization function.
   */
  struct GNUNET_TRANSPORT_PluginFunctions *api;

  /**
   * Short name for the plugin (i.e. "tcp").
   */
  char *short_name;

  /**
   * Name of the library (i.e. "gnunet_plugin_transport_tcp").
   */
  char *lib_name;

  /**
   * List of our known addresses for this transport.
   */
  struct OwnAddressList *addresses;

  /**
   * Environment this transport service is using
   * for this plugin.
   */
  struct GNUNET_TRANSPORT_PluginEnvironment env;

  /**
   * ID of task that is used to clean up expired addresses.
   */
  GNUNET_SCHEDULER_TaskIdentifier address_update_task;

  /**
   * Set to GNUNET_YES if we need to scrap the existing list of
   * "addresses" and start fresh when we receive the next address
   * update from a transport.  Set to GNUNET_NO if we should just add
   * the new address to the list and wait for the commit call.
   */
  int rebuild;

  /**
   * Hashmap of blacklisted peers for this particular transport.
   */
  struct GNUNET_CONTAINER_MultiHashMap *blacklist;
};

struct NeighbourList;

/**
 * For each neighbour we keep a list of messages
 * that we still want to transmit to the neighbour.
 */
struct MessageQueue
{

  /**
   * This is a doubly linked list.
   */
  struct MessageQueue *next;

  /**
   * This is a doubly linked list.
   */
  struct MessageQueue *prev;

  /**
   * The message(s) we want to transmit, GNUNET_MessageHeader(s)
   * stuck together in memory.  Allocated at the end of this struct.
   */
  const char *message_buf;

  /**
   * Size of the message buf
   */
  size_t message_buf_size;

  /**
   * Client responsible for queueing the message;
   * used to check that a client has no two messages
   * pending for the same target.  Can be NULL.
   */
  struct TransportClient *client;

  /**
   * Using which specific address should we send this message?
   */
  struct ForeignAddressList *specific_address;

  /**
   * Peer ID of the Neighbour this entry belongs to.
   */
  struct GNUNET_PeerIdentity neighbour_id;

  /**
   * Plugin that we used for the transmission.
   * NULL until we scheduled a transmission.
   */
  struct TransportPlugin *plugin;

  /**
   * At what time should we fail?
   */
  struct GNUNET_TIME_Absolute timeout;

  /**
   * Internal message of the transport system that should not be
   * included in the usual SEND-SEND_OK transmission confirmation
   * traffic management scheme.  Typically, "internal_msg" will
   * be set whenever "client" is NULL (but it is not strictly
   * required).
   */
  int internal_msg;

  /**
   * How important is the message?
   */
  unsigned int priority;

};


/**
 * For a given Neighbour, which plugins are available
 * to talk to this peer and what are their costs?
 */
struct ReadyList
{
  /**
   * This is a linked list.
   */
  struct ReadyList *next;

  /**
   * Which of our transport plugins does this entry
   * represent?
   */
  struct TransportPlugin *plugin;

  /**
   * Transport addresses, latency, and readiness for
   * this particular plugin.
   */
  struct ForeignAddressList *addresses;

  /**
   * To which neighbour does this ready list belong to?
   */
  struct NeighbourList *neighbour;

};


/**
 * Entry in linked list of all of our current neighbours.
 */
struct NeighbourList
{

  /**
   * This is a linked list.
   */
  struct NeighbourList *next;

  /**
   * Which of our transports is connected to this peer
   * and what is their status?
   */
  struct ReadyList *plugins;

  /**
   * Head of list of messages we would like to send to this peer;
   * must contain at most one message per client.
   */
  struct MessageQueue *messages_head;

  /**
   * Tail of list of messages we would like to send to this peer; must
   * contain at most one message per client.
   */
  struct MessageQueue *messages_tail;

  /**
   * Buffer for at most one payload message used when we receive
   * payload data before our PING-PONG has succeeded.  We then
   * store such messages in this intermediary buffer until the
   * connection is fully up.
   */
  struct GNUNET_MessageHeader *pre_connect_message_buffer;

  /**
   * Context for peerinfo iteration.
   * NULL after we are done processing peerinfo's information.
   */
  struct GNUNET_PEERINFO_IteratorContext *piter;

  /**
   * Public key for this peer.   Valid only if the respective flag is set below.
   */
  struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;

  /**
   * Identity of this neighbour.
   */
  struct GNUNET_PeerIdentity id;

  /**
   * ID of task scheduled to run when this peer is about to
   * time out (will free resources associated with the peer).
   */
  GNUNET_SCHEDULER_TaskIdentifier timeout_task;

  /**
   * ID of task scheduled to run when we should retry transmitting
   * the head of the message queue.  Actually triggered when the
   * transmission is timing out (we trigger instantly when we have
   * a chance of success).
   */
  GNUNET_SCHEDULER_TaskIdentifier retry_task;

  /**
   * How long until we should consider this peer dead
   * (if we don't receive another message in the
   * meantime)?
   */
  struct GNUNET_TIME_Absolute peer_timeout;

  /**
   * Tracker for inbound bandwidth.
   */
  struct GNUNET_BANDWIDTH_Tracker in_tracker;

  /**
   * The latency we have seen for this particular address for
   * this particular peer.  This latency may have been calculated
   * over multiple transports.  This value reflects how long it took
   * us to receive a response when SENDING via this particular
   * transport/neighbour/address combination!
   *
   * FIXME: we need to periodically send PINGs to update this
   * latency (at least more often than the current "huge" (11h?)
   * update interval).
   */
  struct GNUNET_TIME_Relative latency;

  /**
   * How often has the other peer (recently) violated the
   * inbound traffic limit?  Incremented by 10 per violation,
   * decremented by 1 per non-violation (for each
   * time interval).
   */
  unsigned int quota_violation_count;

  /**
   * DV distance to this peer (1 if no DV is used).
   */
  uint32_t distance;

  /**
   * Have we seen an PONG from this neighbour in the past (and
   * not had a disconnect since)?
   */
  int received_pong;

  /**
   * Do we have a valid public key for this neighbour?
   */
  int public_key_valid;

};

/**
 * Message used to ask a peer to validate receipt (to check an address
 * from a HELLO).  Followed by the address we are trying to validate,
 * or an empty address if we are just sending a PING to confirm that a
 * connection which the receiver (of the PING) initiated is still valid.
 */
struct TransportPingMessage
{

  /**
   * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
   */
  struct GNUNET_MessageHeader header;

  /**
   * Challenge code (to ensure fresh reply).
   */
  uint32_t challenge GNUNET_PACKED;

  /**
   * Who is the intended recipient?
   */
  struct GNUNET_PeerIdentity target;

};


/**
 * Message used to validate a HELLO.  The challenge is included in the
 * confirmation to make matching of replies to requests possible.  The
 * signature signs our public key, an expiration time and our address.<p>
 *
 * This message is followed by our transport address that the PING tried
 * to confirm (if we liked it).  The address can be empty (zero bytes)
 * if the PING had not address either (and we received the request via
 * a connection that we initiated).
 */
struct TransportPongMessage
{

  /**
   * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
   */
  struct GNUNET_MessageHeader header;

  /**
   * Challenge code from PING (showing freshness).  Not part of what
   * is signed so that we can re-use signatures.
   */
  uint32_t challenge GNUNET_PACKED;

  /**
   * Signature.
   */
  struct GNUNET_CRYPTO_RsaSignature signature;

  /**
   * What are we signing and why?  Two possible reason codes can be here:
   * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN to confirm that this is a
   * plausible address for this peer (pid is set to identity of signer); or
   * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING to confirm that this is
   * an address we used to connect to the peer with the given pid.
   */
  struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;

  /**
   * When does this signature expire?
   */
  struct GNUNET_TIME_AbsoluteNBO expiration;

  /**
   * Either the identity of the peer Who signed this message, or the
   * identity of the peer that we're connected to using the given
   * address (depending on purpose.type).
   */
  struct GNUNET_PeerIdentity pid;

  /**
   * Size of address appended to this message (part of what is
   * being signed, hence not redundant).
   */
  uint32_t addrlen;

};


/**
 * Linked list of messages to be transmitted to the client.  Each
 * entry is followed by the actual message.
 */
struct ClientMessageQueueEntry
{
  /**
   * This is a doubly-linked list.
   */
  struct ClientMessageQueueEntry *next;

  /**
   * This is a doubly-linked list.
   */
  struct ClientMessageQueueEntry *prev;
};


/**
 * Client connected to the transport service.
 */
struct TransportClient
{

  /**
   * This is a linked list.
   */
  struct TransportClient *next;

  /**
   * Handle to the client.
   */
  struct GNUNET_SERVER_Client *client;

  /**
   * Linked list of messages yet to be transmitted to
   * the client.
   */
  struct ClientMessageQueueEntry *message_queue_head;

  /**
   * Tail of linked list of messages yet to be transmitted to the
   * client.
   */
  struct ClientMessageQueueEntry *message_queue_tail;

  /**
   * Current transmit request handle.
   */
  struct GNUNET_CONNECTION_TransmitHandle *th;

  /**
   * Is a call to "transmit_send_continuation" pending?  If so, we
   * must not free this struct (even if the corresponding client
   * disconnects) and instead only remove it from the linked list and
   * set the "client" field to NULL.
   */
  int tcs_pending;

  /**
   * Length of the list of messages pending for this client.
   */
  unsigned int message_count;

};


/**
 * Context of currently active requests to peerinfo
 * for validation of HELLOs.
 */
struct CheckHelloValidatedContext;


/**
 * Entry in map of all HELLOs awaiting validation.
 */
struct ValidationEntry
{

  /**
   * NULL if this entry is not part of a larger HELLO validation.
   */
  struct CheckHelloValidatedContext *chvc;

  /**
   * The address, actually a pointer to the end
   * of this struct.  Do not free!
   */
  const void *addr;

  /**
   * Name of the transport.
   */
  char *transport_name;

  /**
   * The public key of the peer.
   */
  struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;

  /**
   * ID of task that will clean up this entry if we don't succeed
   * with the validation first.
   */
  GNUNET_SCHEDULER_TaskIdentifier timeout_task;

  /**
   * At what time did we send this validation?
   */
  struct GNUNET_TIME_Absolute send_time;

  /**
   * Session being validated (or NULL for none).
   */
  struct Session *session;

  /**
   * Challenge number we used.
   */
  uint32_t challenge;

  /**
   * Length of addr.
   */
  uint16_t addrlen;

};


/**
 * Context of currently active requests to peerinfo
 * for validation of HELLOs.
 */
struct CheckHelloValidatedContext
{

  /**
   * This is a doubly-linked list.
   */
  struct CheckHelloValidatedContext *next;

  /**
   * This is a doubly-linked list.
   */
  struct CheckHelloValidatedContext *prev;

  /**
   * Hello that we are validating.
   */
  const struct GNUNET_HELLO_Message *hello;

  /**
   * Context for peerinfo iteration.
   * NULL after we are done processing peerinfo's information.
   */
  struct GNUNET_PEERINFO_IteratorContext *piter;

  /**
   * Was a HELLO known for this peer to peerinfo?
   */
  int hello_known;

  /**
   * Number of validation entries currently referring to this
   * CHVC.
   */
  unsigned int ve_count;
};



/**
 * Our HELLO message.
 */
static struct GNUNET_HELLO_Message *our_hello;

/**
 * Our public key.
 */
static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;

/**
 * Our identity.
 */
static struct GNUNET_PeerIdentity my_identity;

/**
 * Our private key.
 */
static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;

/**
 * Our configuration.
 */
const struct GNUNET_CONFIGURATION_Handle *cfg;

/**
 * Linked list of all clients to this service.
 */
static struct TransportClient *clients;

/**
 * All loaded plugins.
 */
static struct TransportPlugin *plugins;

/**
 * Handle to peerinfo service.
 */
static struct GNUNET_PEERINFO_Handle *peerinfo;

/**
 * All known neighbours and their HELLOs.
 */
static struct NeighbourList *neighbours;

/**
 * Number of neighbours we'd like to have.
 */
static uint32_t max_connect_per_transport;

/**
 * Head of linked list.
 */
static struct CheckHelloValidatedContext *chvc_head;

/**
 * Tail of linked list.
 */
static struct CheckHelloValidatedContext *chvc_tail;

/**
 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
 * of the given peer that we are currently validating).
 */
static struct GNUNET_CONTAINER_MultiHashMap *validation_map;

/**
 * Handle for reporting statistics.
 */
static struct GNUNET_STATISTICS_Handle *stats;

/**
 * The peer specified by the given neighbour has timed-out or a plugin
 * has disconnected.  We may either need to do nothing (other plugins
 * still up), or trigger a full disconnect and clean up.  This
 * function updates our state and do the necessary notifications.
 * Also notifies our clients that the neighbour is now officially
 * gone.
 *
 * @param n the neighbour list entry for the peer
 * @param check should we just check if all plugins
 *        disconnected or must we ask all plugins to
 *        disconnect?
 */
static void disconnect_neighbour (struct NeighbourList *n, int check);

/**
 * Check the ready list for the given neighbour and if a plugin is
 * ready for transmission (and if we have a message), do so!
 *
 * @param neighbour target peer for which to transmit
 */
static void try_transmission_to_peer (struct NeighbourList *neighbour);


/**
 * Find an entry in the neighbour list for a particular peer.
 *
 * @return NULL if not found.
 */
static struct NeighbourList *
find_neighbour (const struct GNUNET_PeerIdentity *key)
{
  struct NeighbourList *head = neighbours;

  while ((head != NULL) &&
        (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
    head = head->next;
  return head;
}


/**
 * Find an entry in the transport list for a particular transport.
 *
 * @return NULL if not found.
 */
static struct TransportPlugin *
find_transport (const char *short_name)
{
  struct TransportPlugin *head = plugins;
  while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
    head = head->next;
  return head;
}

/**
 * Is a particular peer blacklisted for a particular transport?
 *
 * @param peer the peer to check for
 * @param plugin the plugin used to connect to the peer
 *
 * @return GNUNET_YES if the peer is blacklisted, GNUNET_NO if not
 */
static int
is_blacklisted (const struct GNUNET_PeerIdentity *peer, struct TransportPlugin *plugin)
{

  if (plugin->blacklist != NULL)
    {
      if (GNUNET_CONTAINER_multihashmap_contains(plugin->blacklist, &peer->hashPubKey) == GNUNET_YES)
        {
#if DEBUG_BLACKLIST
          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                      _("Peer `%s:%s' is blacklisted!\n"),
                      plugin->short_name, GNUNET_i2s (peer));
#endif
          return GNUNET_YES;
        }
    }

  return GNUNET_NO;
}


static void
add_peer_to_blacklist (struct GNUNET_PeerIdentity *peer, char *transport_name)
{
  struct TransportPlugin *plugin;

  plugin = find_transport(transport_name);
  if (plugin == NULL) /* Nothing to do */
    return;
  if (plugin->blacklist == NULL)
    plugin->blacklist = GNUNET_CONTAINER_multihashmap_create(TRANSPORT_BLACKLIST_HT_SIZE);
  GNUNET_assert(plugin->blacklist != NULL);
  GNUNET_CONTAINER_multihashmap_put(plugin->blacklist, &peer->hashPubKey,
				    NULL,
				    GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
}


/**
 * Read the blacklist file, containing transport:peer entries.
 * Provided the transport is loaded, set up hashmap with these
 * entries to blacklist peers by transport.
 *
 */
static void
read_blacklist_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
{
  char *fn;
  char *data;
  size_t pos;
  size_t colon_pos;
  int tsize;
  struct GNUNET_PeerIdentity pid;
  struct stat frstat;
  struct GNUNET_CRYPTO_HashAsciiEncoded enc;
  unsigned int entries_found;
  char *transport_name;

  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_filename (cfg,
                                               "TRANSPORT",
                                               "BLACKLIST_FILE",
                                               &fn))
    {
#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  _("Option `%s' in section `%s' not specified!\n"),
                  "BLACKLIST_FILE",
                  "TRANSPORT");
#endif
      return;
    }
  if (GNUNET_OK != GNUNET_DISK_file_test (fn))
    GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
        | GNUNET_DISK_PERM_USER_WRITE);
  if (0 != STAT (fn, &frstat))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  _("Could not read blacklist file `%s'\n"), fn);
      GNUNET_free (fn);
      return;
    }
  if (frstat.st_size == 0)
    {
#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  _("Blacklist file `%s' is empty.\n"),
                  fn);
#endif
      GNUNET_free (fn);
      return;
    }
  /* FIXME: use mmap */
  data = GNUNET_malloc_large (frstat.st_size);
  GNUNET_assert(data != NULL);
  if (frstat.st_size !=
      GNUNET_DISK_fn_read (fn, data, frstat.st_size))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  _("Failed to read blacklist from `%s'\n"), fn);
      GNUNET_free (fn);
      GNUNET_free (data);
      return;
    }
  entries_found = 0;
  pos = 0;
  while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
    pos++;
  while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
         (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
    {
      colon_pos = pos;
      while ((colon_pos < frstat.st_size) && (data[colon_pos] != ':') && !isspace ( (unsigned char) data[colon_pos]))
        colon_pos++;

      if (colon_pos >= frstat.st_size)
        {
          GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                      _("Syntax error in blacklist file at offset %llu, giving up!\n"),
                      (unsigned long long) colon_pos);
          GNUNET_free (fn);
          GNUNET_free (data);
          return;
        }

      if (isspace( (unsigned char) data[colon_pos]))
      {
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
                    (unsigned long long) colon_pos);
        pos = colon_pos;
        while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
          pos++;
        continue;
      }
      tsize = colon_pos - pos;
      if ((pos >= frstat.st_size) || (pos + tsize >= frstat.st_size) || (tsize == 0))
        {
          GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                      _("Syntax error in blacklist file at offset %llu, giving up!\n"),
                      (unsigned long long) colon_pos);
          GNUNET_free (fn);
          GNUNET_free (data);
          return;
        }

      if (tsize < 1)
        continue;

      transport_name = GNUNET_malloc(tsize + 1);
      memcpy(transport_name, &data[pos], tsize);
      pos = colon_pos + 1;
#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  _("Read transport name %s in blacklist file.\n"),
                  transport_name);
#endif
      memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
      if (!isspace ( (unsigned char) enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
        {
          GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                      _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
                      (unsigned long long) pos);
          pos++;
          while ((pos < frstat.st_size) && (!isspace ( (unsigned char) data[pos])))
            pos++;
          GNUNET_free_non_null(transport_name);
          continue;
        }
      enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
      if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
        {
          GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                      _("Syntax error in blacklist file at offset %llu, skipping bytes `%s'.\n"),
                      (unsigned long long) pos,
                      &enc);
        }
      else
        {
          if (0 != memcmp (&pid,
                           &my_identity,
                           sizeof (struct GNUNET_PeerIdentity)))
            {
              entries_found++;
              add_peer_to_blacklist (&pid,
                                     transport_name);
            }
          else
            {
              GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                          _("Found myself `%s' in blacklist (useless, ignored)\n"),
                          GNUNET_i2s (&pid));
            }
        }
      pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
      GNUNET_free_non_null(transport_name);
      while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
        pos++;
    }
  GNUNET_free (data);
  GNUNET_free (fn);
}


/**
 * Function called to notify a client about the socket being ready to
 * queue more data.  "buf" will be NULL and "size" zero if the socket
 * was closed for writing in the meantime.
 *
 * @param cls closure
 * @param size number of bytes available in buf
 * @param buf where the callee should write the message
 * @return number of bytes written to buf
 */
static size_t
transmit_to_client_callback (void *cls, size_t size, void *buf)
{
  struct TransportClient *client = cls;
  struct ClientMessageQueueEntry *q;
  uint16_t msize;
  size_t tsize;
  const struct GNUNET_MessageHeader *msg;
  char *cbuf;

  client->th = NULL;
  if (buf == NULL)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Transmission to client failed, closing connection.\n");
      /* fatal error with client, free message queue! */
      while (NULL != (q = client->message_queue_head))
        {
	  GNUNET_STATISTICS_update (stats,
				    gettext_noop ("# bytes discarded (could not transmit to client)"),
				    ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
				    GNUNET_NO);
	  GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
				       client->message_queue_tail,
				       q);
          GNUNET_free (q);
        }
      client->message_count = 0;
      return 0;
    }
  cbuf = buf;
  tsize = 0;
  while (NULL != (q = client->message_queue_head))
    {
      msg = (const struct GNUNET_MessageHeader *) &q[1];
      msize = ntohs (msg->size);
      if (msize + tsize > size)
        break;
#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Transmitting message of type %u to client.\n",
                  ntohs (msg->type));
#endif
      GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
				   client->message_queue_tail,
				   q);
      memcpy (&cbuf[tsize], msg, msize);
      tsize += msize;
      GNUNET_free (q);
      client->message_count--;
    }
  if (NULL != q)
    {
      GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
      client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
							msize,
							GNUNET_TIME_UNIT_FOREVER_REL,
							&transmit_to_client_callback,
							client);
      GNUNET_assert (client->th != NULL);
    }
  return tsize;
}


/**
 * Convert an address to a string.
 *
 * @param plugin name of the plugin responsible for the address
 * @param addr binary address
 * @param addr_len number of bytes in addr
 * @return NULL on error, otherwise address string
 */
static const char*
a2s (const char *plugin,
     const void *addr,
     uint16_t addr_len)
{
  struct TransportPlugin *p;

  if (plugin == NULL)
    return NULL;
  p = find_transport (plugin);
  if (p == NULL)
    return NULL;
  return p->api->address_to_string (p->api->cls,
				    addr,
				    addr_len);
}


/**
 * Mark the given FAL entry as 'connected' (and hence preferred for
 * sending); also mark all others for the same peer as 'not connected'
 * (since only one can be preferred).
 *
 * @param fal address to set to 'connected'
 */
static void
mark_address_connected (struct ForeignAddressList *fal)
{
  struct ForeignAddressList *pos;
  int cnt;

  GNUNET_assert (GNUNET_YES == fal->validated);
  if (fal->connected == GNUNET_YES)
    return; /* nothing to do */
  cnt = GNUNET_YES;
  pos = fal->ready_list->addresses;
  while (pos != NULL)
    {
      if (GNUNET_YES == pos->connected)
	{
#if DEBUG_TRANSPORT
	  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		      "Marking address `%s' as no longer connected (due to connect on other address)\n",
		      a2s (pos->ready_list->plugin->short_name,
			   pos->addr,
			   pos->addrlen));
#endif
	  GNUNET_break (cnt == GNUNET_YES);
	  cnt = GNUNET_NO;
	  pos->connected = GNUNET_NO;
	  GNUNET_STATISTICS_update (stats,
				    gettext_noop ("# connected addresses"),
				    -1,
				    GNUNET_NO);
	}
      pos = pos->next;
    }
  fal->connected = GNUNET_YES;
  if (GNUNET_YES == cnt)
    {
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# connected addresses"),
				1,
				GNUNET_NO);
    }
}


/**
 * Send the specified message to the specified client.  Since multiple
 * messages may be pending for the same client at a time, this code
 * makes sure that no message is lost.
 *
 * @param client client to transmit the message to
 * @param msg the message to send
 * @param may_drop can this message be dropped if the
 *        message queue for this client is getting far too large?
 */
static void
transmit_to_client (struct TransportClient *client,
                    const struct GNUNET_MessageHeader *msg, int may_drop)
{
  struct ClientMessageQueueEntry *q;
  uint16_t msize;

  if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  _
                  ("Dropping message of type %u and size %u, have %u messages pending (%u is the soft limit)\n"),
		  ntohs (msg->type),
		  ntohs (msg->size),
                  client->message_count,
		  MAX_PENDING);
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# messages dropped due to slow client"),
				1,
				GNUNET_NO);
      return;
    }
  msize = ntohs (msg->size);
  GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
  q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
  memcpy (&q[1], msg, msize);
  GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
				     client->message_queue_tail,
				     client->message_queue_tail,
				     q);				
  client->message_count++;
  if (client->th == NULL)
    {
      client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
							msize,
							GNUNET_TIME_UNIT_FOREVER_REL,
							&transmit_to_client_callback,
							client);
      GNUNET_assert (client->th != NULL);
    }
}


/**
 * Transmit a 'SEND_OK' notification to the given client for the
 * given neighbour.
 *
 * @param client who to notify
 * @param n neighbour to notify about
 * @param result status code for the transmission request
 */
static void
transmit_send_ok (struct TransportClient *client,
		  struct NeighbourList *n,
		  int result)
{
  struct SendOkMessage send_ok_msg;

  send_ok_msg.header.size = htons (sizeof (send_ok_msg));
  send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
  send_ok_msg.success = htonl (result);
  send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
  send_ok_msg.peer = n->id;
  transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
}


/**
 * Function called by the GNUNET_TRANSPORT_TransmitFunction
 * upon "completion" of a send request.  This tells the API
 * that it is now legal to send another message to the given
 * peer.
 *
 * @param cls closure, identifies the entry on the
 *            message queue that was transmitted and the
 *            client responsible for queueing the message
 * @param target the peer receiving the message
 * @param result GNUNET_OK on success, if the transmission
 *           failed, we should not tell the client to transmit
 *           more messages
 */
static void
transmit_send_continuation (void *cls,
                            const struct GNUNET_PeerIdentity *target,
                            int result)
{
  struct MessageQueue *mq = cls;
  struct NeighbourList *n;

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# bytes pending with plugins"),
			    - (int64_t) mq->message_buf_size,
			    GNUNET_NO);
  if (result == GNUNET_OK)
    {
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# bytes successfully transmitted by plugins"),
				mq->message_buf_size,
				GNUNET_NO);
    }
  else
    {
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# bytes with transmission failure by plugins"),
				mq->message_buf_size,
				GNUNET_NO);
    }
  n = find_neighbour(&mq->neighbour_id);
  GNUNET_assert (n != NULL);
  if (mq->specific_address != NULL)
    {
      if (result == GNUNET_OK)
	{
	  mq->specific_address->timeout =
	    GNUNET_TIME_relative_to_absolute
	    (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
	  if (mq->specific_address->validated == GNUNET_YES)
	    mark_address_connected (mq->specific_address);
	}
      else
	{
	  if (mq->specific_address->connected != GNUNET_NO)
	    {
#if DEBUG_TRANSPORT
	      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
			  "Marking address `%s' as no longer connected (due to transmission problem)\n",
			  a2s (mq->specific_address->ready_list->plugin->short_name,
			       mq->specific_address->addr,
			       mq->specific_address->addrlen));
#endif
	      GNUNET_STATISTICS_update (stats,
					gettext_noop ("# connected addresses"),
					-1,
					GNUNET_NO);
	      mq->specific_address->connected = GNUNET_NO;
	    }
	}
      if (! mq->internal_msg)
	mq->specific_address->in_transmit = GNUNET_NO;
    }
  if (mq->client != NULL)
    transmit_send_ok (mq->client, n, result);
  GNUNET_free (mq);
  try_transmission_to_peer (n);
}


/**
 * Find an address in any of the available transports for
 * the given neighbour that would be good for message
 * transmission.  This is essentially the transport selection
 * routine.
 *
 * @param neighbour for whom to select an address
 * @return selected address, NULL if we have none
 */
struct ForeignAddressList *
find_ready_address(struct NeighbourList *neighbour)
{
  struct ReadyList *head = neighbour->plugins;
  struct ForeignAddressList *addresses;
  struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
  struct ForeignAddressList *best_address;

  best_address = NULL;
  while (head != NULL)
    {
      addresses = head->addresses;
      while (addresses != NULL)
        {
          if ( (addresses->timeout.abs_value < now.abs_value) &&
	       (addresses->connected == GNUNET_YES) )
            {
#if DEBUG_TRANSPORT
              GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                          "Marking long-time inactive connection to `%4s' as down.\n",
                          GNUNET_i2s (&neighbour->id));
#endif
	      GNUNET_STATISTICS_update (stats,
					gettext_noop ("# connected addresses"),
					-1,
					GNUNET_NO);
              addresses->connected = GNUNET_NO;
            }
          addresses = addresses->next;
        }

      addresses = head->addresses;
      while (addresses != NULL)
        {
#if DEBUG_TRANSPORT > 1
	  if (addresses->addr != NULL)
	    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
			"Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
			a2s (head->plugin->short_name,
			     addresses->addr,
			     addresses->addrlen),
			GNUNET_i2s (&neighbour->id),
			addresses->connected,
			addresses->in_transmit,
			addresses->validated,
			addresses->connect_attempts,
			(unsigned long long) addresses->timeout.abs_value,
			(unsigned int) addresses->distance);
#endif
          if ( ( (best_address == NULL) ||
		 (addresses->connected == GNUNET_YES) ||
		 (best_address->connected == GNUNET_NO) ) &&
	       (addresses->in_transmit == GNUNET_NO) &&
	       ( (best_address == NULL) ||
		 (addresses->latency.rel_value < best_address->latency.rel_value)) )
	    best_address = addresses;
	  /* FIXME: also give lower-latency addresses that are not
	     connected a chance some times... */
          addresses = addresses->next;
        }
      head = head->next;
    }
  if (best_address != NULL)
    {
#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Best address found (`%s') has latency of %llu ms.\n",
		  (best_address->addrlen > 0)
		  ? a2s (best_address->ready_list->plugin->short_name,
		       best_address->addr,
		       best_address->addrlen)
		  : "<inbound>",
                  best_address->latency.rel_value);
#endif
    }
  else
    {
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# transmission attempts failed (no address)"),
				1,
				GNUNET_NO);
    }
  return best_address;

}


/**
 * We should re-try transmitting to the given peer,
 * hopefully we've learned something in the meantime.
 */
static void
retry_transmission_task (void *cls,
			 const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct NeighbourList *n = cls;

  n->retry_task = GNUNET_SCHEDULER_NO_TASK;
  try_transmission_to_peer (n);
}


/**
 * Check the ready list for the given neighbour and if a plugin is
 * ready for transmission (and if we have a message), do so!
 *
 * @param neighbour target peer for which to transmit
 */
static void
try_transmission_to_peer (struct NeighbourList *neighbour)
{
  struct ReadyList *rl;
  struct MessageQueue *mq;
  struct GNUNET_TIME_Relative timeout;
  ssize_t ret;
  int force_address;

  if (neighbour->messages_head == NULL)
    {
#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		  "Transmission queue for `%4s' is empty\n",
		  GNUNET_i2s (&neighbour->id));
#endif
      return;                     /* nothing to do */
    }
  rl = NULL;
  mq = neighbour->messages_head;
  force_address = GNUNET_YES;
  if (mq->specific_address == NULL)
    {
      mq->specific_address = find_ready_address(neighbour);
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# transport selected peer address freely"),
				1,
				GNUNET_NO);
      force_address = GNUNET_NO;
    }
  if (mq->specific_address == NULL)
    {
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# transport failed to selected peer address"),
				1,
				GNUNET_NO);
      timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
      if (timeout.rel_value == 0)
	{
#if DEBUG_TRANSPORT
	  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		      "No destination address available to transmit message of size %u to peer `%4s'\n",
		      mq->message_buf_size,
		      GNUNET_i2s (&mq->neighbour_id));
#endif
	  GNUNET_STATISTICS_update (stats,
				    gettext_noop ("# bytes in message queue for other peers"),
				    - (int64_t) mq->message_buf_size,
				    GNUNET_NO);
	  GNUNET_STATISTICS_update (stats,
				    gettext_noop ("# bytes discarded (no destination address available)"),
				    mq->message_buf_size,
				    GNUNET_NO);
	  if (mq->client != NULL)
	    transmit_send_ok (mq->client, neighbour, GNUNET_NO);
	  GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
				       neighbour->messages_tail,
				       mq);
	  GNUNET_free (mq);
	  return;               /* nobody ready */
	}
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# message delivery deferred (no address)"),
				1,
				GNUNET_NO);
      if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
	GNUNET_SCHEDULER_cancel (neighbour->retry_task);
      neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (timeout,
							    &retry_transmission_task,
							    neighbour);
#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		  "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
		  mq->message_buf_size,
		  GNUNET_i2s (&mq->neighbour_id),
		  timeout.rel_value);
#endif
      /* FIXME: might want to trigger peerinfo lookup here
	 (unless that's already pending...) */
      return;
    }
  GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
			       neighbour->messages_tail,
			       mq);
  if (mq->specific_address->connected == GNUNET_NO)
    mq->specific_address->connect_attempts++;
  rl = mq->specific_address->ready_list;
  mq->plugin = rl->plugin;
  if (!mq->internal_msg)
    mq->specific_address->in_transmit = GNUNET_YES;
#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
              mq->message_buf_size,
              GNUNET_i2s (&neighbour->id),
	      (mq->specific_address->addr != NULL)
	      ? a2s (mq->plugin->short_name,
		     mq->specific_address->addr,
		     mq->specific_address->addrlen)
	      : "<inbound>",
	      rl->plugin->short_name);
#endif
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# bytes in message queue for other peers"),
			    - (int64_t) mq->message_buf_size,
			    GNUNET_NO);
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# bytes pending with plugins"),
			    mq->message_buf_size,
			    GNUNET_NO);
  ret = rl->plugin->api->send (rl->plugin->api->cls,
			       &mq->neighbour_id,
			       mq->message_buf,
			       mq->message_buf_size,
			       mq->priority,
			       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
			       mq->specific_address->session,
			       mq->specific_address->addr,
			       mq->specific_address->addrlen,
			       force_address,
			       &transmit_send_continuation, mq);
  if (ret == -1)
    {
      /* failure, but 'send' would not call continuation in this case,
	 so we need to do it here! */
      transmit_send_continuation (mq,
				  &mq->neighbour_id,
				  GNUNET_SYSERR);
    }
}


/**
 * Send the specified message to the specified peer.
 *
 * @param client source of the transmission request (can be NULL)
 * @param peer_address ForeignAddressList where we should send this message
 * @param priority how important is the message
 * @param timeout how long do we have to transmit?
 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
 * @param message_buf_size total size of all messages in message_buf
 * @param is_internal is this an internal message; these are pre-pended and
 *                    also do not count for plugins being "ready" to transmit
 * @param neighbour handle to the neighbour for transmission
 */
static void
transmit_to_peer (struct TransportClient *client,
                  struct ForeignAddressList *peer_address,
                  unsigned int priority,
		  struct GNUNET_TIME_Relative timeout,
                  const char *message_buf,
                  size_t message_buf_size,
                  int is_internal, struct NeighbourList *neighbour)
{
  struct MessageQueue *mq;

#if EXTRA_CHECKS
  if (client != NULL)
    {
      /* check for duplicate submission */
      mq = neighbour->messages_head;
      while (NULL != mq)
        {
          if (mq->client == client)
            {
              /* client transmitted to same peer twice
                 before getting SEND_OK! */
              GNUNET_break (0);
              return;
            }
          mq = mq->next;
        }
    }
#endif
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# bytes in message queue for other peers"),
			    message_buf_size,
			    GNUNET_NO);
  mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
  mq->specific_address = peer_address;
  mq->client = client;
  /* FIXME: this memcpy can be up to 7% of our total runtime! */
  memcpy (&mq[1], message_buf, message_buf_size);
  mq->message_buf = (const char*) &mq[1];
  mq->message_buf_size = message_buf_size;
  memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
  mq->internal_msg = is_internal;
  mq->priority = priority;
  mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
  if (is_internal)
    GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
				 neighbour->messages_tail,
				 mq);
  else
    GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
				       neighbour->messages_tail,
				       neighbour->messages_tail,
				       mq);
  try_transmission_to_peer (neighbour);
}


/**
 * FIXME: document.
 */
struct GeneratorContext
{
  struct TransportPlugin *plug_pos;
  struct OwnAddressList *addr_pos;
  struct GNUNET_TIME_Absolute expiration;
};


/**
 * FIXME: document.
 */
static size_t
address_generator (void *cls, size_t max, void *buf)
{
  struct GeneratorContext *gc = cls;
  size_t ret;

  while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
    {
      gc->plug_pos = gc->plug_pos->next;
      gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
    }
  if (NULL == gc->plug_pos)
    {

      return 0;
    }
  ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
                                  gc->expiration,
                                  &gc->addr_pos[1],
                                  gc->addr_pos->addrlen, buf, max);
  gc->addr_pos = gc->addr_pos->next;
  return ret;
}


/**
 * Construct our HELLO message from all of the addresses of
 * all of the transports.
 */
static void
refresh_hello ()
{
  struct GNUNET_HELLO_Message *hello;
  struct TransportClient *cpos;
  struct NeighbourList *npos;
  struct GeneratorContext gc;

  gc.plug_pos = plugins;
  gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
  gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
  hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
              "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
#endif
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# refreshed my HELLO"),
			    1,
			    GNUNET_NO);
  cpos = clients;
  while (cpos != NULL)
    {
      transmit_to_client (cpos,
                          (const struct GNUNET_MessageHeader *) hello,
                          GNUNET_NO);
      cpos = cpos->next;
    }

  GNUNET_free_non_null (our_hello);
  our_hello = hello;
  GNUNET_PEERINFO_add_peer (peerinfo, our_hello);
  npos = neighbours;
  while (npos != NULL)
    {
#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
                  "Transmitting updated `%s' to neighbour `%4s'\n",
                  "HELLO", GNUNET_i2s (&npos->id));
#endif
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# transmitted my HELLO to other peers"),
				1,
				GNUNET_NO);
      transmit_to_peer (NULL, NULL, 0,
			HELLO_ADDRESS_EXPIRATION,
                        (const char *) our_hello,
			GNUNET_HELLO_size(our_hello),
                        GNUNET_NO, npos);
      npos = npos->next;
    }
}


/**
 * Task used to clean up expired addresses for a plugin.
 *
 * @param cls closure
 * @param tc context
 */
static void
expire_address_task (void *cls,
                     const struct GNUNET_SCHEDULER_TaskContext *tc);


/**
 * Update the list of addresses for this plugin,
 * expiring those that are past their expiration date.
 *
 * @param plugin addresses of which plugin should be recomputed?
 * @param fresh set to GNUNET_YES if a new address was added
 *        and we need to regenerate the HELLO even if nobody
 *        expired
 */
static void
update_addresses (struct TransportPlugin *plugin, 
		  int fresh)
{
  static struct GNUNET_TIME_Absolute last_update;
  struct GNUNET_TIME_Relative min_remaining;
  struct GNUNET_TIME_Relative remaining;
  struct GNUNET_TIME_Absolute now;
  struct OwnAddressList *pos;
  struct OwnAddressList *prev;
  struct OwnAddressList *next;
  int expired;

  if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
    GNUNET_SCHEDULER_cancel (plugin->address_update_task);
  plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
  now = GNUNET_TIME_absolute_get ();
  min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
  expired = (GNUNET_TIME_absolute_get_duration (last_update).rel_value > (HELLO_ADDRESS_EXPIRATION.rel_value / 4));
  prev = NULL;
  pos = plugin->addresses;
  while (pos != NULL)
    {
      next = pos->next;
      if (pos->expires.abs_value < now.abs_value)
        {
          expired = GNUNET_YES;
          if (prev == NULL)
            plugin->addresses = pos->next;
          else
            prev->next = pos->next;
          GNUNET_free (pos);
        }
      else
        {
          remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
          if (remaining.rel_value < min_remaining.rel_value)
            min_remaining = remaining;
          prev = pos;
        }
      pos = next;
    }

  if (expired || fresh)
    {
      last_update = now;
      refresh_hello ();
    }
  min_remaining = GNUNET_TIME_relative_min (min_remaining,
					    GNUNET_TIME_relative_divide (HELLO_ADDRESS_EXPIRATION,
									 2));
  plugin->address_update_task
    = GNUNET_SCHEDULER_add_delayed (min_remaining,
				    &expire_address_task, plugin);
}


/**
 * Task used to clean up expired addresses for a plugin.
 *
 * @param cls closure
 * @param tc context
 */
static void
expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct TransportPlugin *plugin = cls;

  plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
  if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
    update_addresses (plugin, GNUNET_NO);
}


/**
 * Iterator over hash map entries that NULLs the session of validation
 * entries that match the given session.
 *
 * @param cls closure (the 'struct Session*' to match against)
 * @param key current key code (peer ID, not used)
 * @param value value in the hash map ('struct ValidationEntry*')
 * @return GNUNET_YES (we should continue to iterate)
 */
static int
remove_session_validations (void *cls,
			    const GNUNET_HashCode * key,
			    void *value)
{
  struct Session *session = cls;
  struct ValidationEntry *ve = value;

  if (session == ve->session)
    ve->session = NULL;
  return GNUNET_YES;
}


/**
 * We've been disconnected from the other peer (for some
 * connection-oriented transport).  Either quickly
 * re-establish the connection or signal the disconnect
 * to the CORE.
 *
 * Only signal CORE level disconnect if ALL addresses
 * for the peer are exhausted.
 *
 * @param p overall plugin context
 * @param nl neighbour that was disconnected
 */
static void
try_fast_reconnect (struct TransportPlugin *p,
		    struct NeighbourList *nl)
{
  /* FIXME-MW: fast reconnect / transport switching not implemented... */
  /* Note: the idea here is to hide problems with transports (or
     switching between plugins) from the core to eliminate the need to
     re-negotiate session keys and the like; OTOH, we should tell core
     quickly (much faster than timeout) `if a connection was lost and
     could not be re-established (i.e. other peer went down or is
     unable / refuses to communicate);

     So we should consider:
     1) ideally: our own willingness / need to connect
     2) prior failures to connect to this peer (by plugin)
     3) ideally: reasons why other peer terminated (as far as knowable)

     Most importantly, it must be POSSIBLE for another peer to terminate
     a connection for a while (without us instantly re-establishing it).
     Similarly, if another peer is gone we should quickly notify CORE.
     OTOH, if there was a minor glitch (i.e. crash of gnunet-service-transport
     on the other end), we should reconnect in such a way that BOTH CORE
     services never even notice.
     Furthermore, the same mechanism (or small variation) could be used
     to switch to a better-performing plugin (ATS).

     Finally, this needs to be tested throughly... */     							

  /*
   * GNUNET_NO in the call below makes transport disconnect the peer,
   * even if only a single address (out of say, six) went away.  This
   * function must be careful to ONLY disconnect if the peer is gone,
   * not just a specifi address.
   *
   * More specifically, half the places it was used had it WRONG.
   */

  /* No reconnect, signal disconnect instead! */
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
            "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
            "try_fast_reconnect");
  disconnect_neighbour (nl, GNUNET_YES);
}


/**
 * Function that will be called whenever the plugin internally
 * cleans up a session pointer and hence the service needs to
 * discard all of those sessions as well.  Plugins that do not
 * use sessions can simply omit calling this function and always
 * use NULL wherever a session pointer is needed.
 *
 * @param cls closure
 * @param peer which peer was the session for
 * @param session which session is being destoyed
 */
static void
plugin_env_session_end  (void *cls,
			 const struct GNUNET_PeerIdentity *peer,
			 struct Session *session)
{
  struct TransportPlugin *p = cls;
  struct NeighbourList *nl;
  struct ReadyList *rl;
  struct ForeignAddressList *pos;
  struct ForeignAddressList *prev;

  GNUNET_CONTAINER_multihashmap_iterate (validation_map,
					 &remove_session_validations,
					 session);
  nl = find_neighbour (peer);
  if (nl == NULL)
    return; /* was never marked as connected */
  rl = nl->plugins;
  while (rl != NULL)
    {
      if (rl->plugin == p)
	break;
      rl = rl->next;
    }
  if (rl == NULL)
    return; /* was never marked as connected */
  prev = NULL;
  pos = rl->addresses;
  while ( (pos != NULL) &&
	  (pos->session != session) )
    {
      prev = pos;
      pos = pos->next;
    }
  if (pos == NULL)
    return; /* was never marked as connected */
  pos->session = NULL;
  if (pos->addrlen != 0)
    {
      if (nl->received_pong != GNUNET_NO)
	try_fast_reconnect (p, nl);
      return;
    }
  /* was inbound connection, free 'pos' */
  if (prev == NULL)
    rl->addresses = pos->next;
  else
    prev->next = pos->next;
  if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
    {
      GNUNET_SCHEDULER_cancel (pos->revalidate_task);
      pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
    }
  GNUNET_free (pos);
  if (nl->received_pong == GNUNET_NO)
    return; /* nothing to do, never connected... */
  /* check if we have any validated addresses left */
  pos = rl->addresses;
  while (pos != NULL)
    {
      if (pos->validated)
	{
	  try_fast_reconnect (p, nl);
	  return;
	}
      pos = pos->next;
    }
  /* no valid addresses left, signal disconnect! */

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
            "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
            "plugin_env_session_end");
  /* FIXME: This doesn't mean there are no addresses left for this PEER,
   * it means there aren't any left for this PLUGIN/PEER combination! So
   * calling disconnect_neighbor here with GNUNET_NO forces disconnect
   * when it isn't necessary. Using GNUNET_YES at least checks to see
   * if there are any addresses that work first, so as not to overdo it.
   * --NE
   */
  disconnect_neighbour (nl, GNUNET_YES);
}


/**
 * Function that must be called by each plugin to notify the
 * transport service about the addresses under which the transport
 * provided by the plugin can be reached.
 *
 * @param cls closure
 * @param name name of the transport that generated the address
 * @param addr one of the addresses of the host, NULL for the last address
 *        the specific address format depends on the transport
 * @param addrlen length of the address
 * @param expires when should this address automatically expire?
 */
static void
plugin_env_notify_address (void *cls,
                           const char *name,
                           const void *addr,
                           uint16_t addrlen,
                           struct GNUNET_TIME_Relative expires)
{
  struct TransportPlugin *p = cls;
  struct OwnAddressList *al;
  struct GNUNET_TIME_Absolute abex;

  GNUNET_assert (addr != NULL);
  abex = GNUNET_TIME_relative_to_absolute (expires);
  GNUNET_assert (p == find_transport (name));
  al = p->addresses;
  while (al != NULL)
    {
      if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
        {	      
	  al->expires = abex;
	  update_addresses (p, GNUNET_NO);
          return;
        }
      al = al->next;
    }

  al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
  al->next = p->addresses;
  p->addresses = al;
  al->expires = abex;
  al->addrlen = addrlen;
  memcpy (&al[1], addr, addrlen);
  update_addresses (p, GNUNET_YES);
}


/**
 * Notify all of our clients about a peer connecting.
 */
static void
notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
                        struct GNUNET_TIME_Relative latency,
			uint32_t distance)
{
  struct ConnectInfoMessage cim;
  struct TransportClient *cpos;

#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Notifying clients about connection from `%s'\n",
	      GNUNET_i2s (peer));
#endif
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# peers connected"),
			    1,
			    GNUNET_NO);
  cim.header.size = htons (sizeof (struct ConnectInfoMessage));
  cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
  cim.distance = htonl (distance);
  cim.latency = GNUNET_TIME_relative_hton (latency);
  memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
  cpos = clients;
  while (cpos != NULL)
    {
      transmit_to_client (cpos, &cim.header, GNUNET_NO);
      cpos = cpos->next;
    }
}


/**
 * Notify all of our clients about a peer disconnecting.
 */
static void
notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
{
  struct DisconnectInfoMessage dim;
  struct TransportClient *cpos;

#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Notifying clients about lost connection to `%s'\n",
	      GNUNET_i2s (peer));
#endif
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# peers connected"),
			    -1,
			    GNUNET_NO);
  dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
  dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
  dim.reserved = htonl (0);
  memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
  cpos = clients;
  while (cpos != NULL)
    {
      transmit_to_client (cpos, &dim.header, GNUNET_NO);
      cpos = cpos->next;
    }
}


/**
 * Find a ForeignAddressList entry for the given neighbour
 * that matches the given address and transport.
 *
 * @param neighbour which peer we care about
 * @param tname name of the transport plugin
 * @param session session to look for, NULL for 'any'; otherwise
 *        can be used for the service to "learn" this session ID
 *        if 'addr' matches
 * @param addr binary address
 * @param addrlen length of addr
 * @return NULL if no such entry exists
 */
static struct ForeignAddressList *
find_peer_address(struct NeighbourList *neighbour,
		  const char *tname,
		  struct Session *session,
		  const char *addr,
		  uint16_t addrlen)
{
  struct ReadyList *head;
  struct ForeignAddressList *pos;

  head = neighbour->plugins;
  while (head != NULL)
    {
      if (0 == strcmp (tname, head->plugin->short_name))
	break;
      head = head->next;
    }
  if (head == NULL)
    return NULL;
  pos = head->addresses;
  while ( (pos != NULL) &&
	  ( (pos->addrlen != addrlen) ||
	    (memcmp(pos->addr, addr, addrlen) != 0) ) )
    {
      if ( (session != NULL) &&
	   (pos->session == session) )
	return pos;
      pos = pos->next;
    }
  if ( (session != NULL) && (pos != NULL) )
    pos->session = session; /* learn it! */
  return pos;
}


/**
 * Get the peer address struct for the given neighbour and
 * address.  If it doesn't yet exist, create it.
 *
 * @param neighbour which peer we care about
 * @param tname name of the transport plugin
 * @param session session of the plugin, or NULL for none
 * @param addr binary address
 * @param addrlen length of addr
 * @return NULL if we do not have a transport plugin for 'tname'
 */
static struct ForeignAddressList *
add_peer_address (struct NeighbourList *neighbour,
		  const char *tname,
		  struct Session *session,
		  const char *addr,
		  uint16_t addrlen)
{
  struct ReadyList *head;
  struct ForeignAddressList *ret;

  ret = find_peer_address (neighbour, tname, session, addr, addrlen);
  if (ret != NULL)
    return ret;
  head = neighbour->plugins;

  while (head != NULL)
    {
      if (0 == strcmp (tname, head->plugin->short_name))
	break;
      head = head->next;
    }
  if (head == NULL)
    return NULL;
  ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
  ret->session = session;
  if (addrlen > 0)
    {
      ret->addr = (const char*) &ret[1];
      memcpy (&ret[1], addr, addrlen);
    }
  else
    {
      ret->addr = NULL;
    }
  ret->addrlen = addrlen;
  ret->expires = GNUNET_TIME_relative_to_absolute
    (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
  ret->latency = GNUNET_TIME_relative_get_forever();
  ret->distance = -1;
  ret->timeout = GNUNET_TIME_relative_to_absolute
    (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
  ret->ready_list = head;
  ret->next = head->addresses;
  head->addresses = ret;
  return ret;
}


/**
 * Closure for 'add_validated_address'.
 */
struct AddValidatedAddressContext
{
  /**
   * Entry that has been validated.
   */
  const struct ValidationEntry *ve;

  /**
   * Flag set after we have added the address so
   * that we terminate the iteration next time.
   */
  int done;
};


/**
 * Callback function used to fill a buffer of max bytes with a list of
 * addresses in the format used by HELLOs.  Should use
 * "GNUNET_HELLO_add_address" as a helper function.
 *
 * @param cls the 'struct AddValidatedAddressContext' with the validated address
 * @param max maximum number of bytes that can be written to buf
 * @param buf where to write the address information
 * @return number of bytes written, 0 to signal the
 *         end of the iteration.
 */
static size_t
add_validated_address (void *cls,
		       size_t max, void *buf)
{
  struct AddValidatedAddressContext *avac = cls;
  const struct ValidationEntry *ve = avac->ve;

  if (GNUNET_YES == avac->done)
    return 0;
  avac->done = GNUNET_YES;
  return GNUNET_HELLO_add_address (ve->transport_name,
				   GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
				   ve->addr,
				   ve->addrlen,
				   buf,
				   max);
}



/**
 * Closure for 'check_address_exists'.
 */
struct CheckAddressExistsClosure
{
  /**
   * Address to check for.
   */
  const void *addr;

  /**
   * Name of the transport.
   */
  const char *tname;

  /**
   * Session, or NULL.
   */
  struct Session *session;

  /**
   * Set to GNUNET_YES if the address exists.
   */
  int exists;

  /**
   * Length of addr.
   */
  uint16_t addrlen;

};


/**
 * Iterator over hash map entries.  Checks if the given
 * validation entry is for the same address as what is given
 * in the closure.
 *
 * @param cls the 'struct CheckAddressExistsClosure*'
 * @param key current key code (ignored)
 * @param value value in the hash map ('struct ValidationEntry')
 * @return GNUNET_YES if we should continue to
 *         iterate (mismatch), GNUNET_NO if not (entry matched)
 */
static int
check_address_exists (void *cls,
		      const GNUNET_HashCode * key,
		      void *value)
{
  struct CheckAddressExistsClosure *caec = cls;
  struct ValidationEntry *ve = value;

  if ( (0 == strcmp (caec->tname,
		     ve->transport_name)) &&
       (caec->addrlen == ve->addrlen) &&
       (0 == memcmp (caec->addr,
		     ve->addr,
		     caec->addrlen)) )
    {
      caec->exists = GNUNET_YES;
      return GNUNET_NO;
    }
  if ( (ve->session != NULL) &&
       (caec->session == ve->session) )
    {
      caec->exists = GNUNET_YES;
      return GNUNET_NO;
    }
  return GNUNET_YES;
}



/**
 * Iterator to free entries in the validation_map.
 *
 * @param cls closure (unused)
 * @param key current key code
 * @param value value in the hash map (validation to abort)
 * @return GNUNET_YES (always)
 */
static int
abort_validation (void *cls,
		  const GNUNET_HashCode * key,
		  void *value)
{
  struct ValidationEntry *va = value;

  if (GNUNET_SCHEDULER_NO_TASK != va->timeout_task)
    GNUNET_SCHEDULER_cancel (va->timeout_task);
  GNUNET_free (va->transport_name);
  if (va->chvc != NULL)
    {
      va->chvc->ve_count--;
      if (va->chvc->ve_count == 0)
	{
	  GNUNET_CONTAINER_DLL_remove (chvc_head,
				       chvc_tail,
				       va->chvc);
	  GNUNET_free (va->chvc);
	}
      va->chvc = NULL;
    }
  GNUNET_free (va);
  return GNUNET_YES;
}


/**
 * HELLO validation cleanup task (validation failed).
 *
 * @param cls the 'struct ValidationEntry' that failed
 * @param tc scheduler context (unused)
 */
static void
timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct ValidationEntry *va = cls;
  struct GNUNET_PeerIdentity pid;

  va->timeout_task = GNUNET_SCHEDULER_NO_TASK;
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# address validation timeouts"),
			    1,
			    GNUNET_NO);
  GNUNET_CRYPTO_hash (&va->publicKey,
		      sizeof (struct
			      GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
		      &pid.hashPubKey);
  GNUNET_break (GNUNET_OK ==
                GNUNET_CONTAINER_multihashmap_remove (validation_map,
						      &pid.hashPubKey,
						      va));
  abort_validation (NULL, NULL, va);
}


static void
neighbour_timeout_task (void *cls,
		       const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct NeighbourList *n = cls;

#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
              "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
#endif
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# disconnects due to timeout"),
			    1,
			    GNUNET_NO);
  n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
  disconnect_neighbour (n, GNUNET_NO);
}


/**
 * Schedule the job that will cause us to send a PING to the
 * foreign address to evaluate its validity and latency.
 *
 * @param fal address to PING
 */
static void
schedule_next_ping (struct ForeignAddressList *fal);


/**
 * Add the given address to the list of foreign addresses
 * available for the given peer (check for duplicates).
 *
 * @param cls the respective 'struct NeighbourList' to update
 * @param tname name of the transport
 * @param expiration expiration time
 * @param addr the address
 * @param addrlen length of the address
 * @return GNUNET_OK (always)
 */
static int
add_to_foreign_address_list (void *cls,
			     const char *tname,
			     struct GNUNET_TIME_Absolute expiration,
			     const void *addr,
			     uint16_t addrlen)
{
  struct NeighbourList *n = cls;
  struct ForeignAddressList *fal;
  int try;

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# valid peer addresses returned by PEERINFO"),
			    1,
			    GNUNET_NO);
  try = GNUNET_NO;
  fal = find_peer_address (n, tname, NULL, addr, addrlen);
  if (fal == NULL)
    {
#if DEBUG_TRANSPORT_HELLO
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		  "Adding address `%s' (%s) for peer `%4s' due to PEERINFO data for %llums.\n",
		  a2s (tname, addr, addrlen),
		  tname,
		  GNUNET_i2s (&n->id),
		  expiration.abs_value);
#endif
      fal = add_peer_address (n, tname, NULL, addr, addrlen);
      if (fal == NULL)
	{
	  GNUNET_STATISTICS_update (stats,
				    gettext_noop ("# previously validated addresses lacking transport"),
				    1,
				    GNUNET_NO);
	}
      else
	{
	  fal->expires = GNUNET_TIME_absolute_max (expiration,
						   fal->expires);
	  schedule_next_ping (fal);
	}
      try = GNUNET_YES;
    }
  else
    {
      fal->expires = GNUNET_TIME_absolute_max (expiration,
					       fal->expires);
    }
  if (fal == NULL)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		  "Failed to add new address for `%4s'\n",
		  GNUNET_i2s (&n->id));
      return GNUNET_OK;
    }
  if (fal->validated == GNUNET_NO)
    {
      fal->validated = GNUNET_YES;
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# peer addresses considered valid"),
				1,
				GNUNET_NO);
    }
  if (try == GNUNET_YES)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		  "Have new addresses, will try to trigger transmissions.\n");
      try_transmission_to_peer (n);
    }
  return GNUNET_OK;
}


/**
 * Add addresses in validated HELLO "h" to the set of addresses
 * we have for this peer.
 *
 * @param cls closure ('struct NeighbourList*')
 * @param peer id of the peer, NULL for last call
 * @param h hello message for the peer (can be NULL)
 */
static void
add_hello_for_peer (void *cls,
		    const struct GNUNET_PeerIdentity *peer,
		    const struct GNUNET_HELLO_Message *h)
{
  struct NeighbourList *n = cls;

  if (peer == NULL)
    {
      GNUNET_STATISTICS_update (stats,
                                gettext_noop ("# outstanding peerinfo iterate requests"),
                                -1,
                                GNUNET_NO);
      n->piter = NULL;
      return;
    }
  if (h == NULL)
    return; /* no HELLO available */
#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
	      "HELLO",
	      GNUNET_i2s (peer));
#endif
  if (GNUNET_YES != n->public_key_valid)
    {
      GNUNET_HELLO_get_key (h, &n->publicKey);
      n->public_key_valid = GNUNET_YES;
    }
  GNUNET_HELLO_iterate_addresses (h,
				  GNUNET_NO,
				  &add_to_foreign_address_list,
				  n);
}


/**
 * Create a fresh entry in our neighbour list for the given peer.
 * Will try to transmit our current HELLO to the new neighbour.
 * Do not call this function directly, use 'setup_peer_check_blacklist.
 *
 * @param peer the peer for which we create the entry
 * @param do_hello should we schedule transmitting a HELLO
 * @return the new neighbour list entry
 */
static struct NeighbourList *
setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
		     int do_hello)
{
  struct NeighbourList *n;
  struct TransportPlugin *tp;
  struct ReadyList *rl;

#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Setting up state for neighbour `%4s'\n",
	      GNUNET_i2s (peer));
#endif
  GNUNET_assert (our_hello != NULL);
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# active neighbours"),
			    1,
			    GNUNET_NO);
  n = GNUNET_malloc (sizeof (struct NeighbourList));
  n->next = neighbours;
  neighbours = n;
  n->id = *peer;
  n->peer_timeout =
    GNUNET_TIME_relative_to_absolute
    (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
  GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
				 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
				 MAX_BANDWIDTH_CARRY_S);
  tp = plugins;
  while (tp != NULL)
    {
      if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
        {
          rl = GNUNET_malloc (sizeof (struct ReadyList));
	  rl->neighbour = n;
          rl->next = n->plugins;
          n->plugins = rl;
          rl->plugin = tp;
          rl->addresses = NULL;
        }
      tp = tp->next;
    }
  n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
  n->distance = -1;
  n->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
                                                  &neighbour_timeout_task, n);
  if (do_hello)
    {
      GNUNET_STATISTICS_update (stats,
                                gettext_noop ("# peerinfo new neighbor iterate requests"),
                                1,
                                GNUNET_NO);
      GNUNET_STATISTICS_update (stats,
                                gettext_noop ("# outstanding peerinfo iterate requests"),
                                1,
                                GNUNET_NO);
      n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
					  GNUNET_TIME_UNIT_FOREVER_REL,
					  &add_hello_for_peer, n);

      GNUNET_STATISTICS_update (stats,
                                gettext_noop ("# HELLO's sent to new neighbors"),
                                1,
                                GNUNET_NO);
      transmit_to_peer (NULL, NULL, 0,
			HELLO_ADDRESS_EXPIRATION,
			(const char *) our_hello, GNUNET_HELLO_size(our_hello),
			GNUNET_NO, n);
    }
  return n;
}


/**
 * Function called after we have checked if communicating
 * with a given peer is acceptable.
 *
 * @param cls closure
 * @param n NULL if communication is not acceptable
 */
typedef void (*SetupContinuation)(void *cls,
				  struct NeighbourList *n);


/**
 * Information kept for each client registered to perform
 * blacklisting.
 */
struct Blacklisters
{
  /**
   * This is a linked list.
   */
  struct Blacklisters *next;

  /**
   * This is a linked list.
   */
  struct Blacklisters *prev;

  /**
   * Client responsible for this entry.
   */
  struct GNUNET_SERVER_Client *client;

  /**
   * Blacklist check that we're currently performing.
   */
  struct BlacklistCheck *bc;

};


/**
 * Head of DLL of blacklisting clients.
 */
static struct Blacklisters *bl_head;

/**
 * Tail of DLL of blacklisting clients.
 */
static struct Blacklisters *bl_tail;


/**
 * Context we use when performing a blacklist check.
 */
struct BlacklistCheck
{

  /**
   * This is a linked list.
   */
  struct BlacklistCheck *next;

  /**
   * This is a linked list.
   */
  struct BlacklistCheck *prev;

  /**
   * Peer being checked.
   */
  struct GNUNET_PeerIdentity peer;

  /**
   * Option for setup neighbour afterwards.
   */
  int do_hello;

  /**
   * Continuation to call with the result.
   */
  SetupContinuation cont;

  /**
   * Closure for cont.
   */
  void *cont_cls;

  /**
   * Current transmission request handle for this client, or NULL if no
   * request is pending.
   */
  struct GNUNET_CONNECTION_TransmitHandle *th;

  /**
   * Our current position in the blacklisters list.
   */
  struct Blacklisters *bl_pos;

  /**
   * Current task performing the check.
   */
  GNUNET_SCHEDULER_TaskIdentifier task;

};

/**
 * Head of DLL of active blacklisting queries.
 */
static struct BlacklistCheck *bc_head;

/**
 * Tail of DLL of active blacklisting queries.
 */
static struct BlacklistCheck *bc_tail;


/**
 * Perform next action in the blacklist check.
 *
 * @param cls the 'struct BlacklistCheck*'
 * @param tc unused
 */
static void
do_blacklist_check (void *cls,
		    const struct GNUNET_SCHEDULER_TaskContext *tc);


/**
 * Transmit blacklist query to the client.
 *
 * @param cls the 'struct BlacklistCheck'
 * @param size number of bytes allowed
 * @param buf where to copy the message
 * @return number of bytes copied to buf
 */
static size_t
transmit_blacklist_message (void *cls,
			    size_t size,
			    void *buf)
{
  struct BlacklistCheck *bc = cls;
  struct Blacklisters *bl;
  struct BlacklistMessage bm;

  bc->th = NULL;
  if (size == 0)
    {
      GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
      bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
					   bc);
      return 0;
    }
  bl = bc->bl_pos;
  bm.header.size = htons (sizeof (struct BlacklistMessage));
  bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
  bm.is_allowed = htonl (0);
  bm.peer = bc->peer;
  memcpy (buf, &bm, sizeof (bm));
  GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
  return sizeof (bm);
}


/**
 * Perform next action in the blacklist check.
 *
 * @param cls the 'struct BlacklistCheck*'
 * @param tc unused
 */
static void
do_blacklist_check (void *cls,
		    const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct BlacklistCheck *bc = cls;
  struct Blacklisters *bl;

  bc->task = GNUNET_SCHEDULER_NO_TASK;
  bl = bc->bl_pos;
  if (bl == NULL)
    {
      bc->cont (bc->cont_cls,
		setup_new_neighbour (&bc->peer, bc->do_hello));		
      GNUNET_free (bc);
      return;
    }
  if (bl->bc == NULL)
    {
      bl->bc = bc;
      bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
						    sizeof (struct BlacklistMessage),
						    GNUNET_TIME_UNIT_FOREVER_REL,
						    &transmit_blacklist_message,
						    bc);
    }
}


/**
 * Obtain a 'struct NeighbourList' for the given peer.  If such an entry
 * does not yet exist, check the blacklist.  If the blacklist says creating
 * one is acceptable, create one and call the continuation; otherwise
 * call the continuation with NULL.
 *
 * @param peer peer to setup or look up a struct NeighbourList for
 * @param do_hello should we also schedule sending our HELLO to the peer
 *        if this is a new record
 * @param cont function to call with the 'struct NeigbhbourList*'
 * @param cont_cls closure for cont
 */
static void
setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
			    int do_hello,
			    SetupContinuation cont,
			    void *cont_cls)
{
  struct NeighbourList *n;
  struct BlacklistCheck *bc;

  n = find_neighbour(peer);
  if (n != NULL)
    {
      if (cont != NULL)
        cont (cont_cls, n);
      return;
    }
  if (bl_head == NULL)
    {
      if (cont != NULL)
        cont (cont_cls, setup_new_neighbour (peer, do_hello));
      else
        setup_new_neighbour(peer, do_hello);
      return;
    }
  bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
  GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
  bc->peer = *peer;
  bc->do_hello = do_hello;
  bc->cont = cont;
  bc->cont_cls = cont_cls;
  bc->bl_pos = bl_head;
  bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
				       bc);
}


/**
 * Function called with the result of querying a new blacklister about
 * it being allowed (or not) to continue to talk to an existing neighbour.
 *
 * @param cls the original 'struct NeighbourList'
 * @param n NULL if we need to disconnect
 */
static void
confirm_or_drop_neighbour (void *cls,
			   struct NeighbourList *n)
{
  struct NeighbourList * orig = cls;

  if (n == NULL)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&orig->id),
              "confirm_or_drop_neighboUr");
      disconnect_neighbour (orig, GNUNET_NO);
    }
}


/**
 * Handle a request to start a blacklist.
 *
 * @param cls closure (always NULL)
 * @param client identification of the client
 * @param message the actual message
 */
static void
handle_blacklist_init (void *cls,
		       struct GNUNET_SERVER_Client *client,
		       const struct GNUNET_MessageHeader *message)
{
  struct Blacklisters *bl;
  struct BlacklistCheck *bc;
  struct NeighbourList *n;

  bl = bl_head;
  while (bl != NULL)
    {
      if (bl->client == client)
	{
	  GNUNET_break (0);
	  GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
	  return;
	}
      bl = bl->next;
    }
  bl = GNUNET_malloc (sizeof (struct Blacklisters));
  bl->client = client;
  GNUNET_SERVER_client_keep (client);
  GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
  /* confirm that all existing connections are OK! */
  n = neighbours;
  while (NULL != n)
    {
      bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
      GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
      bc->peer = n->id;
      bc->do_hello = GNUNET_NO;
      bc->cont = &confirm_or_drop_neighbour;
      bc->cont_cls = n;
      bc->bl_pos = bl;
      if (n == neighbours) /* all would wait for the same client, no need to
			      create more than just the first task right now */
	bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
					     bc);
      n = n->next;
    }
}


/**
 * Handle a request to blacklist a peer.
 *
 * @param cls closure (always NULL)
 * @param client identification of the client
 * @param message the actual message
 */
static void
handle_blacklist_reply (void *cls,
			struct GNUNET_SERVER_Client *client,
			const struct GNUNET_MessageHeader *message)
{
  const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
  struct Blacklisters *bl;
  struct BlacklistCheck *bc;

  bl = bl_head;
  while ( (bl != NULL) &&
	  (bl->client != client) )
    bl = bl->next;
  if (bl == NULL)
    {
      GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
      return;
    }
  bc = bl->bc;
  bl->bc = NULL;
  if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
    {
      bc->cont (bc->cont_cls, NULL);
      GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
      GNUNET_free (bc);
    }
  else
    {
      bc->bl_pos = bc->bl_pos->next;
      bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
					   bc);
    }
  /* check if any other bc's are waiting for this blacklister */
  bc = bc_head;
  while (bc != NULL)
    {
      if ( (bc->bl_pos == bl) &&
	   (GNUNET_SCHEDULER_NO_TASK == bc->task) )
	bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
					     bc);
      bc = bc->next;
    }
}


/**
 * Send periodic PING messages to a given foreign address.
 *
 * @param cls our 'struct PeriodicValidationContext*'
 * @param tc task context
 */
static void
send_periodic_ping (void *cls,
		    const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct ForeignAddressList *peer_address = cls;
  struct TransportPlugin *tp;
  struct ValidationEntry *va;
  struct NeighbourList *neighbour;
  struct TransportPingMessage ping;
  struct CheckAddressExistsClosure caec;
  char * message_buf;
  uint16_t hello_size;
  size_t slen;
  size_t tsize;

  peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
  if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
    return;
  tp = peer_address->ready_list->plugin;
  neighbour = peer_address->ready_list->neighbour;
  if (GNUNET_YES != neighbour->public_key_valid)
    {
      /* no public key yet, try again later */
      schedule_next_ping (peer_address);
      return;
    }
  caec.addr = peer_address->addr;
  caec.addrlen = peer_address->addrlen;
  caec.tname = tp->short_name;
  caec.session = peer_address->session;
  caec.exists = GNUNET_NO;
  GNUNET_CONTAINER_multihashmap_iterate (validation_map,
                                         &check_address_exists,
                                         &caec);
  if (caec.exists == GNUNET_YES)
    {
      /* During validation attempts we will likely trigger the other
         peer trying to validate our address which in turn will cause
         it to send us its HELLO, so we expect to hit this case rather
         frequently.  Only print something if we are very verbose. */
#if DEBUG_TRANSPORT > 1
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
		  (peer_address->addr != NULL)
                  ? a2s (tp->short_name,
			 peer_address->addr,
			 peer_address->addrlen)
		  : "<inbound>",
                  tp->short_name,
                  GNUNET_i2s (&neighbour->id));
#endif
      schedule_next_ping (peer_address);
      return;
    }
  va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
  va->transport_name = GNUNET_strdup (tp->short_name);
  va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
                                            UINT_MAX);
  va->send_time = GNUNET_TIME_absolute_get();
  va->session = peer_address->session;
  if (peer_address->addr != NULL)
    {
      va->addr = (const void*) &va[1];
      memcpy (&va[1], peer_address->addr, peer_address->addrlen);
      va->addrlen = peer_address->addrlen;
    }
  memcpy(&va->publicKey,
	 &neighbour->publicKey,
	 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));

  va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
                                                   &timeout_hello_validation,
                                                   va);
  GNUNET_CONTAINER_multihashmap_put (validation_map,
                                     &neighbour->id.hashPubKey,
                                     va,
                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);

  if (peer_address->validated != GNUNET_YES)
    hello_size = GNUNET_HELLO_size(our_hello);
  else
    hello_size = 0;

  tsize = sizeof(struct TransportPingMessage) + hello_size;

  if (peer_address->addr != NULL)
    {
      slen = strlen (tp->short_name) + 1;
      tsize += slen + peer_address->addrlen;
    }
  else
    {
      slen = 0; /* make gcc happy */
    }
  message_buf = GNUNET_malloc(tsize);
  ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
  ping.challenge = htonl(va->challenge);
  memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
  if (peer_address->validated != GNUNET_YES)
    {
      memcpy(message_buf, our_hello, hello_size);
    }

  if (peer_address->addr != NULL)
    {
      ping.header.size = htons(sizeof(struct TransportPingMessage) +
			       peer_address->addrlen +
			       slen);
      memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
	     tp->short_name,
	     slen);
      memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
	     peer_address->addr,
	     peer_address->addrlen);
    }
  else
    {
      ping.header.size = htons(sizeof(struct TransportPingMessage));
    }

  memcpy(&message_buf[hello_size],
         &ping,
         sizeof(struct TransportPingMessage));

#if DEBUG_TRANSPORT_REVALIDATION
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s'\n",
              (peer_address->addr != NULL)
	      ? a2s (peer_address->plugin->short_name,
		     peer_address->addr,
		     peer_address->addrlen)
	      : "<inbound>",
              tp->short_name,
              GNUNET_i2s (&neighbour->id),
              "HELLO", hello_size,
              "PING");
#endif
  if (peer_address->validated != GNUNET_YES)
    GNUNET_STATISTICS_update (stats,
                              gettext_noop ("# PING with HELLO messages sent"),
                              1,
                              GNUNET_NO);
  else
    GNUNET_STATISTICS_update (stats,
                              gettext_noop ("# PING without HELLO messages sent"),
                              1,
                              GNUNET_NO);
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# PING messages sent for re-validation"),
			    1,
			    GNUNET_NO);
  transmit_to_peer (NULL, peer_address,
                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
                    HELLO_VERIFICATION_TIMEOUT,
                    message_buf, tsize,
                    GNUNET_YES, neighbour);
  GNUNET_free(message_buf);
  schedule_next_ping (peer_address);
}


/**
 * Schedule the job that will cause us to send a PING to the
 * foreign address to evaluate its validity and latency.
 *
 * @param fal address to PING
 */
static void
schedule_next_ping (struct ForeignAddressList *fal)
{
  struct GNUNET_TIME_Relative delay;

  if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
    return;
  delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
  delay.rel_value /= 2; /* do before expiration */
  delay = GNUNET_TIME_relative_min (delay,
				    LATENCY_EVALUATION_MAX_DELAY);
  if (GNUNET_YES != fal->estimated)
    {
      delay = GNUNET_TIME_UNIT_ZERO;
      fal->estimated = GNUNET_YES;
    }				
  if (GNUNET_YES == fal->connected)
    {
      delay = GNUNET_TIME_relative_min (delay,
					CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
    }
  /* FIXME: also adjust delay based on how close the last
     observed latency is to the latency of the best alternative */
  /* bound how fast we can go */
  delay = GNUNET_TIME_relative_max (delay,
				    GNUNET_TIME_UNIT_SECONDS);
  /* randomize a bit (to avoid doing all at the same time) */
  delay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
  fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(delay,
						      &send_periodic_ping,
						      fal);
}




/**
 * Function that will be called if we receive some payload
 * from another peer.
 *
 * @param message the payload
 * @param n peer who claimed to be the sender
 */
static void
handle_payload_message (const struct GNUNET_MessageHeader *message,
			struct NeighbourList *n)
{
  struct InboundMessage *im;
  struct TransportClient *cpos;
  uint16_t msize;

  msize = ntohs (message->size);
  if (n->received_pong == GNUNET_NO)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Received message of type %u and size %u from `%4s', but no pong yet!!\n",
                  ntohs (message->type),
                  ntohs (message->size),
                  GNUNET_i2s (&n->id));
      GNUNET_free_non_null (n->pre_connect_message_buffer);
      n->pre_connect_message_buffer = GNUNET_malloc (msize);
      memcpy (n->pre_connect_message_buffer, message, msize);
      return;
    }

#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Received message of type %u and size %u from `%4s', sending to all clients.\n",
	      ntohs (message->type),
	      ntohs (message->size),
	      GNUNET_i2s (&n->id));
#endif
  if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
						      (ssize_t) msize))
    {
      n->quota_violation_count++;
#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,			
		  "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
		  n->in_tracker.available_bytes_per_s__,
		  n->quota_violation_count);
#endif
      /* Discount 32k per violation */
      GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
					- 32 * 1024);		
    }
  else
    {
      if (n->quota_violation_count > 0)
	{
	  /* try to add 32k back */
	  GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
					    32 * 1024);
	  n->quota_violation_count--;
	}
    }
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# payload received from other peers"),
			    msize,
			    GNUNET_NO);
  /* transmit message to all clients */
  im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
  im->header.size = htons (sizeof (struct InboundMessage) + msize);
  im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
  im->latency = GNUNET_TIME_relative_hton (n->latency);
  im->peer = n->id;
  im->distance = ntohl(n->distance);
  memcpy (&im[1], message, msize);
  cpos = clients;
  while (cpos != NULL)
    {
      transmit_to_client (cpos, &im->header, GNUNET_YES);
      cpos = cpos->next;
    }
  GNUNET_free (im);
}


/**
 * Iterator over hash map entries.  Checks if the given validation
 * entry is for the same challenge as what is given in the PONG.
 *
 * @param cls the 'struct TransportPongMessage*'
 * @param key peer identity
 * @param value value in the hash map ('struct ValidationEntry')
 * @return GNUNET_YES if we should continue to
 *         iterate (mismatch), GNUNET_NO if not (entry matched)
 */
static int
check_pending_validation (void *cls,
			  const GNUNET_HashCode * key,
			  void *value)
{
  const struct TransportPongMessage *pong = cls;
  struct ValidationEntry *ve = value;
  struct AddValidatedAddressContext avac;
  unsigned int challenge = ntohl(pong->challenge);
  struct GNUNET_HELLO_Message *hello;
  struct GNUNET_PeerIdentity target;
  struct NeighbourList *n;
  struct ForeignAddressList *fal;
  struct OwnAddressList *oal;
  struct TransportPlugin *tp;
  struct GNUNET_MessageHeader *prem;
  uint16_t ps;
  const char *addr;
  size_t slen;
  size_t alen;

  ps = ntohs (pong->header.size);
  if (ps < sizeof (struct TransportPongMessage))
    {
      GNUNET_break_op (0);
      return GNUNET_NO;
    }
  addr = (const char*) &pong[1];
  slen = strlen (ve->transport_name) + 1;
  if ( (ps - sizeof (struct TransportPongMessage) < slen) ||
       (ve->challenge != challenge) ||
       (addr[slen-1] != '\0') ||
       (0 != strcmp (addr, ve->transport_name)) ||
       (ntohl (pong->purpose.size)
	!= sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
	sizeof (uint32_t) +
	sizeof (struct GNUNET_TIME_AbsoluteNBO) +
	sizeof (struct GNUNET_PeerIdentity) + ps - sizeof (struct TransportPongMessage)) )
    {
      return GNUNET_YES;
    }

  alen = ps - sizeof (struct TransportPongMessage) - slen;
  switch (ntohl (pong->purpose.purpose))
    {
    case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN:
      if ( (ve->addrlen + slen != ntohl (pong->addrlen)) ||
	   (0 != memcmp (&addr[slen],
			 ve->addr,
			 ve->addrlen)) )
        {
          return GNUNET_YES; /* different entry, keep trying! */
        }
      if (0 != memcmp (&pong->pid,
		       key,
		       sizeof (struct GNUNET_PeerIdentity)))
	{
	  GNUNET_break_op (0);
	  return GNUNET_NO;
	}
      if (GNUNET_OK !=
	  GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
				    &pong->purpose,
				    &pong->signature,
				    &ve->publicKey))
	{
	  GNUNET_break_op (0);
	  return GNUNET_NO;
	}

#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		  "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
		  GNUNET_h2s (key),
		  a2s (ve->transport_name,
		       (const struct sockaddr *) ve->addr,
		       ve->addrlen),
		  ve->transport_name);
#endif
      break;
    case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING:
      if (0 != memcmp (&pong->pid,
			 &my_identity,
			 sizeof (struct GNUNET_PeerIdentity)))
	{
	  GNUNET_break_op (0);
	  return GNUNET_NO;
	}
      if (ve->addrlen != 0)
        {
          /* must have been for a different validation entry */
          return GNUNET_YES;
        }
      tp = find_transport (ve->transport_name);
      if (tp == NULL)
	{
	  GNUNET_break (0);
	  return GNUNET_YES;
	}
      oal = tp->addresses;
      while (NULL != oal)
	{
	  if ( (oal->addrlen == alen) &&
	       (0 == memcmp (&oal[1],
			     &addr[slen],
			     alen)) )
	    break;
	  oal = oal->next;
	}
      if (oal == NULL)
	{
	  GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		      _("Not accepting PONG with address `%s' since I cannot confirm having this address.\n"),
		      a2s (ve->transport_name,
			   &addr[slen],
			   alen));
	  return GNUNET_NO;	
	}
      if (GNUNET_OK !=
	  GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING,
				    &pong->purpose,
				    &pong->signature,
				    &ve->publicKey))
	{
	  GNUNET_break_op (0);
	  return GNUNET_NO;
	}

#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		  "Confirmed that peer `%4s' is talking to us using address `%s' (%s) for us.\n",
		  GNUNET_h2s (key),
		  a2s (ve->transport_name,
		       &addr[slen],
		       alen),
		  ve->transport_name);
#endif
      break;
    default:
      GNUNET_break_op (0);
      return GNUNET_NO;
    }
  if (GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
		  _("Received expired signature.  Check system time.\n"));
      return GNUNET_NO;
    }
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# address validation successes"),
			    1,
			    GNUNET_NO);
  /* create the updated HELLO */
  GNUNET_CRYPTO_hash (&ve->publicKey,
                      sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
                      &target.hashPubKey);
  if (ve->addr != NULL)
    {
      avac.done = GNUNET_NO;
      avac.ve = ve;
      hello = GNUNET_HELLO_create (&ve->publicKey,
				   &add_validated_address,
				   &avac);
      GNUNET_PEERINFO_add_peer (peerinfo,
				hello);
      GNUNET_free (hello);
    }
  n = find_neighbour (&target);
  if (n != NULL)
    {
      n->publicKey = ve->publicKey;
      n->public_key_valid = GNUNET_YES;
      fal = add_peer_address (n,
			      ve->transport_name,
			      ve->session,
			      ve->addr,
			      ve->addrlen);
      GNUNET_assert (fal != NULL);
      fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
      fal->validated = GNUNET_YES;
      mark_address_connected (fal);
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# peer addresses considered valid"),
				1,
				GNUNET_NO);
      fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
      schedule_next_ping (fal);
      if (n->latency.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
	n->latency = fal->latency;
      else
	n->latency.rel_value = (fal->latency.rel_value + n->latency.rel_value) / 2;

      n->distance = fal->distance;
      if (GNUNET_NO == n->received_pong)
	{
	  n->received_pong = GNUNET_YES;
	  notify_clients_connect (&target, n->latency, n->distance);
	  if (NULL != (prem = n->pre_connect_message_buffer))
	    {
	      n->pre_connect_message_buffer = NULL;
	      handle_payload_message (prem, n);
	      GNUNET_free (prem);
	    }
	}
      if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
	{
	  GNUNET_SCHEDULER_cancel (n->retry_task);
	  n->retry_task = GNUNET_SCHEDULER_NO_TASK;
	  try_transmission_to_peer (n);
	}
    }

  /* clean up validation entry */
  GNUNET_assert (GNUNET_YES ==
		 GNUNET_CONTAINER_multihashmap_remove (validation_map,
						       key,
						       ve));
  abort_validation (NULL, NULL, ve);
  return GNUNET_NO;
}


/**
 * Function that will be called if we receive a validation
 * of an address challenge that we transmitted to another
 * peer.  Note that the validation should only be considered
 * acceptable if the challenge matches AND if the sender
 * address is at least a plausible address for this peer
 * (otherwise we may be seeing a MiM attack).
 *
 * @param cls closure
 * @param message the pong message
 * @param peer who responded to our challenge
 * @param sender_address string describing our sender address (as observed
 *         by the other peer in binary format)
 * @param sender_address_len number of bytes in 'sender_address'
 */
static void
handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
             const struct GNUNET_PeerIdentity *peer,
             const char *sender_address,
             size_t sender_address_len)
{
#if DEBUG_TRANSPORT > 1
  /* we get tons of these that just get discarded, only log
     if we are quite verbose */
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Receiving `%s' message from `%4s'.\n", "PONG",
	      GNUNET_i2s (peer));
#endif
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# PONG messages received"),
			    1,
			    GNUNET_NO);
  if (GNUNET_SYSERR !=
      GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
						  &peer->hashPubKey,
						  &check_pending_validation,
						  (void*) message))
    {
      /* This is *expected* to happen a lot since we send
	 PONGs to *all* known addresses of the sender of
	 the PING, so most likely we get multiple PONGs
	 per PING, and all but the first PONG will end up
	 here. So really we should not print anything here
	 unless we want to be very, very verbose... */
#if DEBUG_TRANSPORT > 2
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
                  "PONG",
		  GNUNET_i2s (peer),
		  "PING");
#endif
      return;
    }

}


/**
 * Try to validate a neighbour's address by sending him our HELLO and a PING.
 *
 * @param cls the 'struct ValidationEntry*'
 * @param neighbour neighbour to validate, NULL if validation failed
 */
static void
transmit_hello_and_ping (void *cls,
			 struct NeighbourList *neighbour)
{
  struct ValidationEntry *va = cls;
  struct ForeignAddressList *peer_address;
  struct TransportPingMessage ping;
  uint16_t hello_size;
  size_t tsize;
  char * message_buf;
  struct GNUNET_PeerIdentity id;
  size_t slen;

  GNUNET_CRYPTO_hash (&va->publicKey,
		      sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
		      &id.hashPubKey);
  if (neighbour == NULL)
    {
      /* FIXME: stats... */
      GNUNET_break (GNUNET_OK ==
		    GNUNET_CONTAINER_multihashmap_remove (validation_map,
							  &id.hashPubKey,
							  va));
      abort_validation (NULL, NULL, va);
      return;
    }
  neighbour->publicKey = va->publicKey;
  neighbour->public_key_valid = GNUNET_YES;
  peer_address = add_peer_address (neighbour,
				   va->transport_name, NULL,
				   (const void*) &va[1],
				   va->addrlen);
  if (peer_address == NULL)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Failed to add peer `%4s' for plugin `%s'\n",
                  GNUNET_i2s (&neighbour->id),
		  va->transport_name);
      GNUNET_break (GNUNET_OK ==
		    GNUNET_CONTAINER_multihashmap_remove (validation_map,
							  &id.hashPubKey,
							  va));
      abort_validation (NULL, NULL, va);
      return;
    }
  hello_size = GNUNET_HELLO_size(our_hello);
  slen = strlen(va->transport_name) + 1;
  tsize = sizeof(struct TransportPingMessage) + hello_size + va->addrlen + slen;
  message_buf = GNUNET_malloc(tsize);
  ping.challenge = htonl(va->challenge);
  ping.header.size = htons(sizeof(struct TransportPingMessage) + slen + va->addrlen);
  ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
  memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
  memcpy(message_buf, our_hello, hello_size);
  memcpy(&message_buf[hello_size],
	 &ping,
	 sizeof(struct TransportPingMessage));
  memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
	 va->transport_name,
	 slen);
  memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
	 &va[1],
	 va->addrlen);
#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
	      (va->addrlen == 0)
	      ? "<inbound>"
	      : a2s (va->transport_name,
		     (const void*) &va[1], va->addrlen),
	      va->transport_name,
	      GNUNET_i2s (&neighbour->id),
	      "HELLO", hello_size,
	      "PING", sizeof (struct TransportPingMessage) + va->addrlen + slen);
#endif

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# PING messages sent for initial validation"),
			    1,
			    GNUNET_NO);
  transmit_to_peer (NULL, peer_address,
		    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
		    HELLO_VERIFICATION_TIMEOUT,
		    message_buf, tsize,
		    GNUNET_YES, neighbour);
  GNUNET_free(message_buf);
}


/**
 * Check if the given address is already being validated; if not,
 * append the given address to the list of entries that are being be
 * validated and initiate validation.
 *
 * @param cls closure ('struct CheckHelloValidatedContext *')
 * @param tname name of the transport
 * @param expiration expiration time
 * @param addr the address
 * @param addrlen length of the address
 * @return GNUNET_OK (always)
 */
static int
run_validation (void *cls,
                const char *tname,
                struct GNUNET_TIME_Absolute expiration,
                const void *addr,
		uint16_t addrlen)
{
  struct CheckHelloValidatedContext *chvc = cls;
  struct GNUNET_PeerIdentity id;
  struct TransportPlugin *tp;
  struct ValidationEntry *va;
  struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
  struct CheckAddressExistsClosure caec;
  struct OwnAddressList *oal;

  GNUNET_assert (addr != NULL);

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# peer addresses scheduled for validation"),
			    1,
			    GNUNET_NO);
  tp = find_transport (tname);
  if (tp == NULL)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO |
                  GNUNET_ERROR_TYPE_BULK,
                  _
                  ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
                  tname);
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# peer addresses not validated (plugin not available)"),
				1,
				GNUNET_NO);
      return GNUNET_OK;
    }
  /* check if this is one of our own addresses */
  oal = tp->addresses;
  while (NULL != oal)
    {
      if ( (oal->addrlen == addrlen) &&
	   (0 == memcmp (&oal[1],
			 addr,
			 addrlen)) )
	{
	  /* not plausible, this address is equivalent to our own address! */
	  GNUNET_STATISTICS_update (stats,
				    gettext_noop ("# peer addresses not validated (loopback)"),
				    1,
				    GNUNET_NO);
	  return GNUNET_OK;
	}
      oal = oal->next;
    }
  GNUNET_HELLO_get_key (chvc->hello, &pk);
  GNUNET_CRYPTO_hash (&pk,
                      sizeof (struct
                              GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
                      &id.hashPubKey);

  if (is_blacklisted(&id, tp))
    {
#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Attempted to validate blacklisted peer `%s' using `%s'!\n",
		  GNUNET_i2s(&id),
		  tname);
#endif
      return GNUNET_OK;
    }

  caec.addr = addr;
  caec.addrlen = addrlen;
  caec.session = NULL;
  caec.tname = tname;
  caec.exists = GNUNET_NO;
  GNUNET_CONTAINER_multihashmap_iterate (validation_map,
					 &check_address_exists,
					 &caec);
  if (caec.exists == GNUNET_YES)
    {
      /* During validation attempts we will likely trigger the other
	 peer trying to validate our address which in turn will cause
	 it to send us its HELLO, so we expect to hit this case rather
	 frequently.  Only print something if we are very verbose. */
#if DEBUG_TRANSPORT > 1
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		  "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
		  a2s (tname, addr, addrlen),
		  tname,
		  GNUNET_i2s (&id));
#endif
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# peer addresses not validated (in progress)"),
				1,
				GNUNET_NO);
      return GNUNET_OK;
    }
  va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
  va->chvc = chvc;
  chvc->ve_count++;
  va->transport_name = GNUNET_strdup (tname);
  va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
                                            UINT_MAX);
  va->send_time = GNUNET_TIME_absolute_get();
  va->addr = (const void*) &va[1];
  memcpy (&va[1], addr, addrlen);
  va->addrlen = addrlen;
  GNUNET_HELLO_get_key (chvc->hello,
			&va->publicKey);
  va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
						   &timeout_hello_validation,
						   va);
  GNUNET_CONTAINER_multihashmap_put (validation_map,
				     &id.hashPubKey,
				     va,
				     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
  setup_peer_check_blacklist (&id, GNUNET_NO,
			      &transmit_hello_and_ping,
			      va);
  return GNUNET_OK;
}


/**
 * Check if addresses in validated hello "h" overlap with
 * those in "chvc->hello" and validate the rest.
 *
 * @param cls closure
 * @param peer id of the peer, NULL for last call
 * @param h hello message for the peer (can be NULL)
 */
static void
check_hello_validated (void *cls,
                       const struct GNUNET_PeerIdentity *peer,
                       const struct GNUNET_HELLO_Message *h)
{
  struct CheckHelloValidatedContext *chvc = cls;
  struct GNUNET_HELLO_Message *plain_hello;
  struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
  struct GNUNET_PeerIdentity target;
  struct NeighbourList *n;

  if (peer == NULL)
    {
      GNUNET_STATISTICS_update (stats,
                                gettext_noop ("# outstanding peerinfo iterate requests"),
                                -1,
                                GNUNET_NO);
      chvc->piter = NULL;
      if (GNUNET_NO == chvc->hello_known)
	{
	  /* notify PEERINFO about the peer now, so that we at least
	     have the public key if some other component needs it */
	  GNUNET_HELLO_get_key (chvc->hello, &pk);
	  GNUNET_CRYPTO_hash (&pk,
			      sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
			      &target.hashPubKey);
	  plain_hello = GNUNET_HELLO_create (&pk,
					     NULL,
					     NULL);
	  GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
	  GNUNET_free (plain_hello);
#if DEBUG_TRANSPORT_HELLO
	  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		      "PEERINFO had no `%s' message for peer `%4s', full validation needed.\n",
		      "HELLO",
		      GNUNET_i2s (&target));
#endif
	  GNUNET_STATISTICS_update (stats,
				    gettext_noop ("# new HELLOs requiring full validation"),
				    1,
				    GNUNET_NO);
	  GNUNET_HELLO_iterate_addresses (chvc->hello,
					  GNUNET_NO,
					  &run_validation,
					  chvc);
	}
      else
	{
	  GNUNET_STATISTICS_update (stats,
				    gettext_noop ("# duplicate HELLO (peer known)"),
				    1,
				    GNUNET_NO);
	}
      chvc->ve_count--;
      if (chvc->ve_count == 0)
	{
	  GNUNET_CONTAINER_DLL_remove (chvc_head,
				       chvc_tail,
				       chvc);
	  GNUNET_free (chvc);	
	}
      return;
    }
  if (h == NULL)
    return;
#if DEBUG_TRANSPORT_HELLO
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "PEERINFO had `%s' message for peer `%4s', validating only new addresses.\n",
	      "HELLO",
	      GNUNET_i2s (peer));
#endif
  chvc->hello_known = GNUNET_YES;
  n = find_neighbour (peer);
  if (n != NULL)
    {
#if DEBUG_TRANSPORT_HELLO
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Calling hello_iterate_addresses for %s!\n",
                  GNUNET_i2s (peer));
#endif
      GNUNET_HELLO_iterate_addresses (h,
				      GNUNET_NO,
				      &add_to_foreign_address_list,
				      n);
      try_transmission_to_peer (n);
    }
  else
    {
#if DEBUG_TRANSPORT_HELLO
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "No existing neighbor record for %s!\n",
                  GNUNET_i2s (peer));
#endif
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# no existing neighbour record (validating HELLO)"),
				1,
				GNUNET_NO);
    }
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# HELLO validations (update case)"),
			    1,
			    GNUNET_NO);
  GNUNET_HELLO_iterate_new_addresses (chvc->hello,
				      h,
				      GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
				      &run_validation,
				      chvc);
}


/**
 * Process HELLO-message.
 *
 * @param plugin transport involved, may be NULL
 * @param message the actual message
 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
 */
static int
process_hello (struct TransportPlugin *plugin,
               const struct GNUNET_MessageHeader *message)
{
  uint16_t hsize;
  struct GNUNET_PeerIdentity target;
  const struct GNUNET_HELLO_Message *hello;
  struct CheckHelloValidatedContext *chvc;
  struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
#if DEBUG_TRANSPORT_HELLO > 2
  char *my_id;
#endif
  hsize = ntohs (message->size);
  if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
      (hsize < sizeof (struct GNUNET_MessageHeader)))
    {
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# HELLOs received for validation"),
			    1,
			    GNUNET_NO);

  /* first, check if load is too high */
  if (GNUNET_SCHEDULER_get_load (GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
    {
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# HELLOs ignored due to high load"),
				1,
				GNUNET_NO);
#if DEBUG_TRANSPORT_HELLO
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Ignoring `%s' for `%4s', load too high.\n",
                  "HELLO",
                  GNUNET_i2s (&target));
#endif
      return GNUNET_OK;
    }
  hello = (const struct GNUNET_HELLO_Message *) message;
  if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
    {
#if DEBUG_TRANSPORT_HELLO
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Unable to get public key from `%s' for `%4s'!\n",
                  "HELLO",
                  GNUNET_i2s (&target));
#endif
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }

  GNUNET_CRYPTO_hash (&publicKey,
                      sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
                      &target.hashPubKey);

#if DEBUG_TRANSPORT_HELLO
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Received `%s' message for `%4s'\n",
              "HELLO",
              GNUNET_i2s (&target));
#endif

  if (0 == memcmp (&my_identity,
		   &target,
		   sizeof (struct GNUNET_PeerIdentity)))
    {
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
				1,
				GNUNET_NO);
      return GNUNET_OK;
    }
  chvc = chvc_head;
  while (NULL != chvc)
    {
      if (GNUNET_HELLO_equals (hello,
			       chvc->hello,
			       GNUNET_TIME_absolute_get ()).abs_value > 0)
	{
#if DEBUG_TRANSPORT_HELLO > 2
	  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		      "Received duplicate `%s' message for `%4s'; ignored\n",
		      "HELLO",
		      GNUNET_i2s (&target));
#endif
	  return GNUNET_OK; /* validation already pending */
	}
      if (GNUNET_HELLO_size(hello) == GNUNET_HELLO_size (chvc->hello))
	GNUNET_break (0 != memcmp (hello, chvc->hello,
				   GNUNET_HELLO_size(hello)));
      chvc = chvc->next;
    }

#if BREAK_TESTS
  struct NeighbourList *temp_neighbor = find_neighbour(&target);
  if ((NULL != temp_neighbor))
    {
      fprintf(stderr, "Already know peer, ignoring hello\n");
      return GNUNET_OK;
    }
#endif

#if DEBUG_TRANSPORT_HELLO > 2
  if (plugin != NULL)
    {
      my_id = GNUNET_strdup(GNUNET_i2s(plugin->env.my_identity));
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "%s: Starting validation of `%s' message for `%4s' via '%s' of size %u\n",
                  my_id,
                  "HELLO",
                  GNUNET_i2s (&target),
                  plugin->short_name,
                  GNUNET_HELLO_size(hello));
      GNUNET_free(my_id);
    }
#endif
  chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
  chvc->ve_count = 1;
  chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
  memcpy (&chvc[1], hello, hsize);
  GNUNET_CONTAINER_DLL_insert (chvc_head,
			       chvc_tail,
			       chvc);
  /* finally, check if HELLO was previously validated
     (continuation will then schedule actual validation) */
  GNUNET_STATISTICS_update (stats,
                            gettext_noop ("# peerinfo process hello iterate requests"),
                            1,
                            GNUNET_NO);
  GNUNET_STATISTICS_update (stats,
                            gettext_noop ("# outstanding peerinfo iterate requests"),
                            1,
                            GNUNET_NO);
  chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
                                         &target,
                                         HELLO_VERIFICATION_TIMEOUT,
                                         &check_hello_validated, chvc);
  return GNUNET_OK;
}


/**
 * The peer specified by the given neighbour has timed-out or a plugin
 * has disconnected.  We may either need to do nothing (other plugins
 * still up), or trigger a full disconnect and clean up.  This
 * function updates our state and does the necessary notifications.
 * Also notifies our clients that the neighbour is now officially
 * gone.
 *
 * @param n the neighbour list entry for the peer
 * @param check GNUNET_YES to check if ALL addresses for this peer
 *              are gone, GNUNET_NO to force a disconnect of the peer
 *              regardless of whether other addresses exist.
 */
static void
disconnect_neighbour (struct NeighbourList *n, int check)
{
  struct ReadyList *rpos;
  struct NeighbourList *npos;
  struct NeighbourList *nprev;
  struct MessageQueue *mq;
  struct ForeignAddressList *peer_addresses;
  struct ForeignAddressList *peer_pos;

  if (GNUNET_YES == check)
    {
      rpos = n->plugins;
      while (NULL != rpos)
        {
          peer_addresses = rpos->addresses;
          while (peer_addresses != NULL)
            {
              if (GNUNET_YES == peer_addresses->connected)
                {
                  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                            "NOT Disconnecting from `%4s', still have live addresses!\n",
                            GNUNET_i2s (&n->id));
                  return;             /* still connected */
                }
              peer_addresses = peer_addresses->next;
            }
          rpos = rpos->next;
        }
    }
#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
              "Disconnecting from `%4s'\n",
	      GNUNET_i2s (&n->id));
#endif
  /* remove n from neighbours list */
  nprev = NULL;
  npos = neighbours;
  while ((npos != NULL) && (npos != n))
    {
      nprev = npos;
      npos = npos->next;
    }
  GNUNET_assert (npos != NULL);
  if (nprev == NULL)
    neighbours = n->next;
  else
    nprev->next = n->next;

  /* notify all clients about disconnect */
  if (GNUNET_YES == n->received_pong)
    notify_clients_disconnect (&n->id);

  /* clean up all plugins, cancel connections and pending transmissions */
  while (NULL != (rpos = n->plugins))
    {
      n->plugins = rpos->next;
      rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
      while (rpos->addresses != NULL)
        {
          peer_pos = rpos->addresses;
          rpos->addresses = peer_pos->next;
	  if (peer_pos->connected == GNUNET_YES)
	    GNUNET_STATISTICS_update (stats,
				      gettext_noop ("# connected addresses"),
				      -1,
				      GNUNET_NO);
	  if (GNUNET_YES == peer_pos->validated)
	    GNUNET_STATISTICS_update (stats,
				      gettext_noop ("# peer addresses considered valid"),
				      -1,
				      GNUNET_NO);
	  if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
	    {
	      GNUNET_SCHEDULER_cancel (peer_pos->revalidate_task);
	      peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
	    }
          GNUNET_free(peer_pos);
        }
      GNUNET_free (rpos);
    }

  /* free all messages on the queue */
  while (NULL != (mq = n->messages_head))
    {
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# bytes in message queue for other peers"),
				- (int64_t) mq->message_buf_size,
				GNUNET_NO);
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# bytes discarded due to disconnect"),
				mq->message_buf_size,
				GNUNET_NO);
      GNUNET_CONTAINER_DLL_remove (n->messages_head,
				   n->messages_tail,
				   mq);
      GNUNET_assert (0 == memcmp(&mq->neighbour_id,
				 &n->id,
				 sizeof(struct GNUNET_PeerIdentity)));
      GNUNET_free (mq);
    }
  if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
    {
      GNUNET_SCHEDULER_cancel (n->timeout_task);
      n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
    }
  if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
    {
      GNUNET_SCHEDULER_cancel (n->retry_task);
      n->retry_task = GNUNET_SCHEDULER_NO_TASK;
    }
  if (n->piter != NULL)
    {
      GNUNET_PEERINFO_iterate_cancel (n->piter);
      GNUNET_STATISTICS_update (stats,
                                gettext_noop ("# outstanding peerinfo iterate requests"),
                                -1,
                                GNUNET_NO);
      n->piter = NULL;
    }
  /* finally, free n itself */
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# active neighbours"),
			    -1,
			    GNUNET_NO);
  GNUNET_free_non_null (n->pre_connect_message_buffer);
  GNUNET_free (n);
}


/**
 * We have received a PING message from someone.  Need to send a PONG message
 * in response to the peer by any means necessary.
 */
static int
handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
	    const struct GNUNET_PeerIdentity *peer,
	    struct Session *session,
	    const char *sender_address,
	    uint16_t sender_address_len)
{
  struct TransportPlugin *plugin = cls;
  struct SessionHeader *session_header = (struct SessionHeader*) session;
  struct TransportPingMessage *ping;
  struct TransportPongMessage *pong;
  struct NeighbourList *n;
  struct ReadyList *rl;
  struct ForeignAddressList *fal;
  struct OwnAddressList *oal;
  const char *addr;
  size_t alen;
  size_t slen;

  if (ntohs (message->size) < sizeof (struct TransportPingMessage))
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }

  ping = (struct TransportPingMessage *) message;
  if (0 != memcmp (&ping->target,
                   plugin->env.my_identity,
                   sizeof (struct GNUNET_PeerIdentity)))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  _("Received `%s' message from `%s' destined for `%s' which is not me!\n"),
		  "PING",
		  (sender_address != NULL)
		  ? a2s (plugin->short_name,
			 (const struct sockaddr *)sender_address,
			 sender_address_len)
		  : "<inbound>",
		  GNUNET_i2s (&ping->target));
      return GNUNET_SYSERR;
    }
#if DEBUG_PING_PONG
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
	      "Processing `%s' from `%s'\n",
	      "PING",
	      (sender_address != NULL)
	      ? a2s (plugin->short_name,
		     (const struct sockaddr *)sender_address,
		     sender_address_len)
	      : "<inbound>");
#endif
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# PING messages received"),
			    1,
			    GNUNET_NO);
  addr = (const char*) &ping[1];
  alen = ntohs (message->size) - sizeof (struct TransportPingMessage);
  slen = strlen (plugin->short_name) + 1;
  if (alen == 0)
    {
      /* peer wants to confirm that we have an outbound connection to him */
      if (session == NULL)
	{
	  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
		      _("Refusing to create PONG since I do not have a session with `%s'.\n"),
		      GNUNET_i2s (peer));
	  return GNUNET_SYSERR;
	}
      pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len + slen);
      pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len + slen);
      pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
      pong->purpose.size =
	htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
	       sizeof (uint32_t) +
	       sizeof (struct GNUNET_TIME_AbsoluteNBO) +
	       sizeof (struct GNUNET_PeerIdentity) + sender_address_len + slen);
      pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING);
      pong->challenge = ping->challenge;
      pong->addrlen = htonl(sender_address_len + slen);
      memcpy(&pong->pid,
	     peer,
	     sizeof(struct GNUNET_PeerIdentity));
      memcpy (&pong[1],
	      plugin->short_name,
	      slen);
      memcpy (&((char*)&pong[1])[slen],
	      sender_address,
	      sender_address_len);
      if (GNUNET_TIME_absolute_get_remaining (session_header->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4)
	{
	  /* create / update cached sig */
#if DEBUG_TRANSPORT
	  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		      "Creating PONG signature to indicate active connection.\n");
#endif
	  session_header->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
	  pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
	  GNUNET_assert (GNUNET_OK ==
			 GNUNET_CRYPTO_rsa_sign (my_private_key,
						 &pong->purpose,
						 &session_header->pong_signature));
	}
      else
	{
	  pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
	}
      memcpy (&pong->signature,
	      &session_header->pong_signature,
	      sizeof (struct GNUNET_CRYPTO_RsaSignature));


    }
  else
    {
      /* peer wants to confirm that this is one of our addresses */
      addr += slen;
      alen -= slen;
      if (GNUNET_OK !=
	  plugin->api->check_address (plugin->api->cls,
				      addr,
				      alen))
	{
	  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
		      _("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
		      a2s (plugin->short_name,
			   addr,
			   alen));
	  return GNUNET_NO;
	}
      oal = plugin->addresses;
      while (NULL != oal)
	{
	  if ( (oal->addrlen == alen) &&
	       (0 == memcmp (addr,
			     &oal[1],
			     alen)) )
	    break;
	  oal = oal->next;
	}
      pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
      pong->header.size = htons (sizeof (struct TransportPongMessage) + alen + slen);
      pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
      pong->purpose.size =
	htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
	       sizeof (uint32_t) +
	       sizeof (struct GNUNET_TIME_AbsoluteNBO) +
	       sizeof (struct GNUNET_PeerIdentity) + alen + slen);
      pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
      pong->challenge = ping->challenge;
      pong->addrlen = htonl(alen + slen);
      memcpy(&pong->pid,
	     &my_identity,
	     sizeof(struct GNUNET_PeerIdentity));
      memcpy (&pong[1], plugin->short_name, slen);
      memcpy (&((char*)&pong[1])[slen], addr, alen);
      if ( (oal != NULL) &&
	   (GNUNET_TIME_absolute_get_remaining (oal->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4) )
	{
	  /* create / update cached sig */
#if DEBUG_TRANSPORT
	  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		      "Creating PONG signature to indicate ownership.\n");
#endif
	  oal->pong_sig_expires = GNUNET_TIME_absolute_min (oal->expires,
							    GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
	  pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
	  GNUNET_assert (GNUNET_OK ==
			 GNUNET_CRYPTO_rsa_sign (my_private_key,
						 &pong->purpose,
						 &oal->pong_signature));	
	  memcpy (&pong->signature,
		  &oal->pong_signature,
		  sizeof (struct GNUNET_CRYPTO_RsaSignature));
	}
      else if (oal == NULL)
	{
	  /* not using cache (typically DV-only) */
	  pong->expiration = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
	  GNUNET_assert (GNUNET_OK ==
			 GNUNET_CRYPTO_rsa_sign (my_private_key,
						 &pong->purpose,
						 &pong->signature));	
	}
      else
	{
	  /* can used cached version */
	  pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
	  memcpy (&pong->signature,
		  &oal->pong_signature,
		  sizeof (struct GNUNET_CRYPTO_RsaSignature));
	}
    }
  n = find_neighbour(peer);
  GNUNET_assert (n != NULL);
  /* first try reliable response transmission */
  rl = n->plugins;
  while (rl != NULL)
    {
      fal = rl->addresses;
      while (fal != NULL)
	{
	  if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
					   peer,
					   (const char*) pong,
					   ntohs (pong->header.size),
					   TRANSPORT_PONG_PRIORITY,
					   HELLO_VERIFICATION_TIMEOUT,
					   fal->session,
					   fal->addr,
					   fal->addrlen,
					   GNUNET_SYSERR,
					   NULL, NULL))
	    {
	      /* done! */
	      GNUNET_STATISTICS_update (stats,
					gettext_noop ("# PONGs unicast via reliable transport"),
					1,
					GNUNET_NO);
	      GNUNET_free (pong);
	      return GNUNET_OK;
	    }
	  fal = fal->next;
	}
      rl = rl->next;
    }
  /* no reliable method found, do multicast */
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# PONGs multicast to all available addresses"),
			    1,
			    GNUNET_NO);
  rl = n->plugins;
  while (rl != NULL)
    {
      fal = rl->addresses;
      while (fal != NULL)
	{
	  transmit_to_peer(NULL, fal,
			   TRANSPORT_PONG_PRIORITY,
			   HELLO_VERIFICATION_TIMEOUT,
			   (const char *)pong,
			   ntohs(pong->header.size),
			   GNUNET_YES,
			   n);
	  fal = fal->next;
	}
      rl = rl->next;
    }
  GNUNET_free(pong);
  return GNUNET_OK;
}


/**
 * Function called by the plugin for each received message.
 * Update data volumes, possibly notify plugins about
 * reducing the rate at which they read from the socket
 * and generally forward to our receive callback.
 *
 * @param cls the "struct TransportPlugin *" we gave to the plugin
 * @param peer (claimed) identity of the other peer
 * @param message the message, NULL if we only care about
 *                learning about the delay until we should receive again
 * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
 * @param session identifier used for this session (can be NULL)
 * @param sender_address binary address of the sender (if observed)
 * @param sender_address_len number of bytes in sender_address
 * @return how long in ms the plugin should wait until receiving more data
 *         (plugins that do not support this, can ignore the return value)
 */
static struct GNUNET_TIME_Relative
plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
                    const struct GNUNET_MessageHeader *message,
                    uint32_t distance,
		    struct Session *session,
		    const char *sender_address,
                    uint16_t sender_address_len)
{
  struct TransportPlugin *plugin = cls;
  struct ReadyList *service_context;
  struct ForeignAddressList *peer_address;
  uint16_t msize;
  struct NeighbourList *n;
  struct GNUNET_TIME_Relative ret;
  if (is_blacklisted (peer, plugin))
    return GNUNET_TIME_UNIT_FOREVER_REL;

  n = find_neighbour (peer);
  if (n == NULL)
    n = setup_new_neighbour (peer, GNUNET_YES);
  service_context = n->plugins;
  while ((service_context != NULL) && (plugin != service_context->plugin))
    service_context = service_context->next;
  GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
  peer_address = NULL;
  if (message != NULL)
    {
      if ( (session != NULL) ||
	   (sender_address != NULL) )
	peer_address = add_peer_address (n,
					 plugin->short_name,
					 session,
					 sender_address,
					 sender_address_len);
      if (peer_address != NULL)
	{
	  peer_address->distance = distance;
	  if (GNUNET_YES == peer_address->validated)
	    mark_address_connected (peer_address);
	  peer_address->timeout
	    =
	    GNUNET_TIME_relative_to_absolute
	    (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
	  schedule_next_ping (peer_address);
	}
      /* update traffic received amount ... */
      msize = ntohs (message->size);
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# bytes received from other peers"),
				msize,
				GNUNET_NO);
      n->distance = distance;
      n->peer_timeout =
	GNUNET_TIME_relative_to_absolute
	(GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
      GNUNET_SCHEDULER_cancel (n->timeout_task);
      n->timeout_task =
	GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
				      &neighbour_timeout_task, n);
      if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
	{
	  /* dropping message due to frequent inbound volume violations! */
	  GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
		      GNUNET_ERROR_TYPE_BULK,
		      _
		      ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
		      n->in_tracker.available_bytes_per_s__,
		      n->quota_violation_count);
	  GNUNET_STATISTICS_update (stats,
				    gettext_noop ("# bandwidth quota violations by other peers"),
				    1,
				    GNUNET_NO);
	  return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
	}

#if DEBUG_PING_PONG
          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                      "Received message of type %u and size %u from `%4s', sending to all clients.\n",
                      ntohs (message->type),
                      ntohs (message->size),
		      GNUNET_i2s (peer));
#endif
      switch (ntohs (message->type))
	{
	case GNUNET_MESSAGE_TYPE_HELLO:
	  GNUNET_STATISTICS_update (stats,
				    gettext_noop ("# HELLO messages received from other peers"),
				    1,
				    GNUNET_NO);
	  process_hello (plugin, message);
	  break;
	case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
	  handle_ping (plugin, message, peer, session, sender_address, sender_address_len);
	  break;
	case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
	  handle_pong (plugin, message, peer, sender_address, sender_address_len);
	  break;
	default:
	  handle_payload_message (message, n);
	  break;
	}
    }
  ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
  if (ret.rel_value > 0)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		  "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
		  (unsigned long long) n->in_tracker.consumption_since_last_update__,
		  (unsigned int) n->in_tracker.available_bytes_per_s__,
		  (unsigned long long) ret.rel_value);
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# ms throttling suggested"),
				(int64_t) ret.rel_value,
				GNUNET_NO);
    }
  return ret;
}

/**
 * Handle START-message.  This is the first message sent to us
 * by any client which causes us to add it to our list.
 *
 * @param cls closure (always NULL)
 * @param client identification of the client
 * @param message the actual message
 */
static void
handle_start (void *cls,
              struct GNUNET_SERVER_Client *client,
              const struct GNUNET_MessageHeader *message)
{
  const struct StartMessage *start;
  struct TransportClient *c;
  struct ConnectInfoMessage cim;
  struct NeighbourList *n;

  start = (const struct StartMessage*) message;
#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Received `%s' request from client\n", "START");
#endif
  c = clients;
  while (c != NULL)
    {
      if (c->client == client)
        {
          /* client already on our list! */
          GNUNET_break (0);
          GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
          return;
        }
      c = c->next;
    }
  if ( (GNUNET_NO != ntohl (start->do_check)) &&
       (0 != memcmp (&start->self,
		     &my_identity,
		     sizeof (struct GNUNET_PeerIdentity))) )
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		  _("Rejecting control connection from peer `%s', which is not me!\n"),
		  GNUNET_i2s (&start->self));
      GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
      return;
    }
  c = GNUNET_malloc (sizeof (struct TransportClient));
  c->next = clients;
  clients = c;
  c->client = client;
  if (our_hello != NULL)
    {
#if DEBUG_TRANSPORT
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Sending our own `%s' to new client\n", "HELLO");
#endif
      transmit_to_client (c,
                          (const struct GNUNET_MessageHeader *) our_hello,
                          GNUNET_NO);
      /* tell new client about all existing connections */
      cim.header.size = htons (sizeof (struct ConnectInfoMessage));
      cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
      n = neighbours;
      while (n != NULL)
	{
	  if (GNUNET_YES == n->received_pong)
	    {
	      cim.id = n->id;
	      cim.latency = GNUNET_TIME_relative_hton (n->latency);
	      cim.distance = htonl (n->distance);
	      transmit_to_client (c, &cim.header, GNUNET_NO);
            }
	    n = n->next;
        }
    }
  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}


/**
 * Handle HELLO-message.
 *
 * @param cls closure (always NULL)
 * @param client identification of the client
 * @param message the actual message
 */
static void
handle_hello (void *cls,
              struct GNUNET_SERVER_Client *client,
              const struct GNUNET_MessageHeader *message)
{
  int ret;

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# HELLOs received from clients"),
			    1,
			    GNUNET_NO);
  ret = process_hello (NULL, message);
  GNUNET_SERVER_receive_done (client, ret);
}


/**
 * Closure for 'transmit_client_message'; followed by
 * 'msize' bytes of the actual message.
 */
struct TransmitClientMessageContext
{
  /**
   * Client on whom's behalf we are sending.
   */
  struct GNUNET_SERVER_Client *client;

  /**
   * Timeout for the transmission.
   */
  struct GNUNET_TIME_Absolute timeout;

  /**
   * Message priority.
   */
  uint32_t priority;

  /**
   * Size of the message in bytes.
   */
  uint16_t msize;
};


/**
 * Schedule transmission of a message we got from a client to a peer.
 *
 * @param cls the 'struct TransmitClientMessageContext*'
 * @param n destination, or NULL on error (in that case, drop the message)
 */
static void
transmit_client_message (void *cls,
			 struct NeighbourList *n)
{
  struct TransmitClientMessageContext *tcmc = cls;
  struct TransportClient *tc;

  tc = clients;
  while ((tc != NULL) && (tc->client != tcmc->client))
    tc = tc->next;

  if (n != NULL)
    {
      transmit_to_peer (tc, NULL, tcmc->priority,
			GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
			(char *)&tcmc[1],
			tcmc->msize, GNUNET_NO, n);
    }
  GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
  GNUNET_SERVER_client_drop (tcmc->client);
  GNUNET_free (tcmc);
}


/**
 * Handle SEND-message.
 *
 * @param cls closure (always NULL)
 * @param client identification of the client
 * @param message the actual message
 */
static void
handle_send (void *cls,
             struct GNUNET_SERVER_Client *client,
             const struct GNUNET_MessageHeader *message)
{
  const struct OutboundMessage *obm;
  const struct GNUNET_MessageHeader *obmm;
  struct TransmitClientMessageContext *tcmc;
  uint16_t size;
  uint16_t msize;

  size = ntohs (message->size);
  if (size <
      sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
    {
      GNUNET_break (0);
      GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
      return;
    }
  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# payload received for other peers"),
			    size,
			    GNUNET_NO);
  obm = (const struct OutboundMessage *) message;
  obmm = (const struct GNUNET_MessageHeader *) &obm[1];
  msize = size - sizeof (struct OutboundMessage);

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
              "SEND", GNUNET_i2s (&obm->peer),
              ntohs (obmm->type),
              msize);

  tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
  tcmc->client = client;
  tcmc->priority = ntohl (obm->priority);
  tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
  tcmc->msize = msize;
  /* FIXME: this memcpy can be up to 7% of our total runtime */
  memcpy (&tcmc[1], obmm, msize);
  GNUNET_SERVER_client_keep (client);
  setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
			      &transmit_client_message,
			      tcmc);
}


/**
 * Handle request connect message
 *
 * @param cls closure (always NULL)
 * @param client identification of the client
 * @param message the actual message
 */
static void
handle_request_connect (void *cls,
                        struct GNUNET_SERVER_Client *client,
                        const struct GNUNET_MessageHeader *message)
{
  const struct TransportRequestConnectMessage *trcm =
    (const struct TransportRequestConnectMessage *) message;

  GNUNET_STATISTICS_update (stats,
                            gettext_noop ("# REQUEST CONNECT messages received"),
                            1,
                            GNUNET_NO);
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received a request connect message for peer %s\n", GNUNET_i2s(&trcm->peer));
  setup_peer_check_blacklist (&trcm->peer, GNUNET_YES,
                              NULL, NULL);
  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}

/**
 * Handle SET_QUOTA-message.
 *
 * @param cls closure (always NULL)
 * @param client identification of the client
 * @param message the actual message
 */
static void
handle_set_quota (void *cls,
                  struct GNUNET_SERVER_Client *client,
                  const struct GNUNET_MessageHeader *message)
{
  const struct QuotaSetMessage *qsm =
    (const struct QuotaSetMessage *) message;
  struct NeighbourList *n;

  GNUNET_STATISTICS_update (stats,
			    gettext_noop ("# SET QUOTA messages received"),
			    1,
			    GNUNET_NO);
  n = find_neighbour (&qsm->peer);
  if (n == NULL)
    {
      GNUNET_SERVER_receive_done (client, GNUNET_OK);
      GNUNET_STATISTICS_update (stats,
				gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
				1,
				GNUNET_NO);
      return;
    }
#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
              "SET_QUOTA",
	      (unsigned int) ntohl (qsm->quota.value__),
	      (unsigned int) n->in_tracker.available_bytes_per_s__,
	      GNUNET_i2s (&qsm->peer));
#endif
  GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
					 qsm->quota);
  if (0 == ntohl (qsm->quota.value__))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&n->id),
                "SET_QUOTA");
      disconnect_neighbour (n, GNUNET_NO);
    }
  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}


/**
 * Take the given address and append it to the set of results sent back to
 * the client.
 *
 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
 * @param address the resolved name, NULL to indicate the last response
 */
static void
transmit_address_to_client (void *cls, const char *address)
{
  struct GNUNET_SERVER_TransmitContext *tc = cls;
  size_t slen;

  if (NULL == address)
    slen = 0;
  else
    slen = strlen (address) + 1;

  GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
					      GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
  if (NULL == address)
    GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
}


/**
 * Handle AddressLookup-message.
 *
 * @param cls closure (always NULL)
 * @param client identification of the client
 * @param message the actual message
 */
static void
handle_address_lookup (void *cls,
                       struct GNUNET_SERVER_Client *client,
                       const struct GNUNET_MessageHeader *message)
{
  const struct AddressLookupMessage *alum;
  struct TransportPlugin *lsPlugin;
  const char *nameTransport;
  const char *address;
  uint16_t size;
  struct GNUNET_SERVER_TransmitContext *tc;
  struct GNUNET_TIME_Absolute timeout;
  struct GNUNET_TIME_Relative rtimeout;
  int32_t numeric;

  size = ntohs (message->size);
  if (size < sizeof (struct AddressLookupMessage))
    {
      GNUNET_break_op (0);
      GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
      return;
    }
  alum = (const struct AddressLookupMessage *) message;
  uint32_t addressLen = ntohl (alum->addrlen);
  if (size <= sizeof (struct AddressLookupMessage) + addressLen)
    {
      GNUNET_break_op (0);
      GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
      return;
    }
  address = (const char *) &alum[1];
  nameTransport = (const char *) &address[addressLen];
  if (nameTransport
      [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
    {
      GNUNET_break_op (0);
      GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
      return;
    }
  timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
  rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
  numeric = ntohl (alum->numeric_only);
  lsPlugin = find_transport (nameTransport);
  if (NULL == lsPlugin)
    {
      tc = GNUNET_SERVER_transmit_context_create (client);
      GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
						  GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
      GNUNET_SERVER_transmit_context_run (tc, rtimeout);
      return;
    }
  tc = GNUNET_SERVER_transmit_context_create (client);
  lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
					 nameTransport,
                                         address, addressLen,
					 numeric,
                                         rtimeout,
                                         &transmit_address_to_client, tc);
}


/**
 * Setup the environment for this plugin.
 */
static void
create_environment (struct TransportPlugin *plug)
{
  plug->env.cfg = cfg;
  plug->env.my_identity = &my_identity;
  plug->env.our_hello = &our_hello;
  plug->env.cls = plug;
  plug->env.receive = &plugin_env_receive;
  plug->env.notify_address = &plugin_env_notify_address;
  plug->env.session_end = &plugin_env_session_end;
  plug->env.max_connections = max_connect_per_transport;
  plug->env.stats = stats;
}


/**
 * Start the specified transport (load the plugin).
 */
static void
start_transport (struct GNUNET_SERVER_Handle *server,
		 const char *name)
{
  struct TransportPlugin *plug;
  char *libname;

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              _("Loading `%s' transport plugin\n"), name);
  GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
  plug = GNUNET_malloc (sizeof (struct TransportPlugin));
  create_environment (plug);
  plug->short_name = GNUNET_strdup (name);
  plug->lib_name = libname;
  plug->next = plugins;
  plugins = plug;
  plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
  if (plug->api == NULL)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  _("Failed to load transport plugin for `%s'\n"), name);
      GNUNET_free (plug->short_name);
      plugins = plug->next;
      GNUNET_free (libname);
      GNUNET_free (plug);
    }
}


/**
 * Called whenever a client is disconnected.  Frees our
 * resources associated with that client.
 *
 * @param cls closure
 * @param client identification of the client
 */
static void
client_disconnect_notification (void *cls,
                                struct GNUNET_SERVER_Client *client)
{
  struct TransportClient *pos;
  struct TransportClient *prev;
  struct ClientMessageQueueEntry *mqe;
  struct Blacklisters *bl;
  struct BlacklistCheck *bc;

  if (client == NULL)
    return;
#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
              "Client disconnected, cleaning up.\n");
#endif
  /* clean up blacklister */
  bl = bl_head;
  while (bl != NULL)
    {
      if (bl->client == client)
	{
	  bc = bc_head;
	  while (bc != NULL)
	    {
	      if (bc->bl_pos == bl)
		{
		  bc->bl_pos = bl->next;
		  if (bc->th != NULL)
		    {
		      GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
		      bc->th = NULL;		
		    }
		  if (bc->task == GNUNET_SCHEDULER_NO_TASK)
		    bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
							 bc);
		  break;
		}
	      bc = bc->next;
	    }
	  GNUNET_CONTAINER_DLL_remove (bl_head,
				       bl_tail,
				       bl);
	  GNUNET_SERVER_client_drop (bl->client);
	  GNUNET_free (bl);
	  break;
	}
      bl = bl->next;
    }
  /* clean up 'normal' clients */
  prev = NULL;
  pos = clients;
  while ((pos != NULL) && (pos->client != client))
    {
      prev = pos;
      pos = pos->next;
    }
  if (pos == NULL)
    return;
  while (NULL != (mqe = pos->message_queue_head))
    {
      GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
				   pos->message_queue_tail,
				   mqe);
      pos->message_count--;
      GNUNET_free (mqe);
    }
  if (prev == NULL)
    clients = pos->next;
  else
    prev->next = pos->next;
  if (GNUNET_YES == pos->tcs_pending)
    {
      pos->client = NULL;
      return;
    }
  if (pos->th != NULL)
    {
      GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
      pos->th = NULL;
    }
  GNUNET_break (0 == pos->message_count);
  GNUNET_free (pos);
}


/**
 * Function called when the service shuts down.  Unloads our plugins
 * and cancels pending validations.
 *
 * @param cls closure, unused
 * @param tc task context (unused)
 */
static void
shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct TransportPlugin *plug;
  struct OwnAddressList *al;
  struct CheckHelloValidatedContext *chvc;

  while (neighbours != NULL)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&neighbours->id),
              "SHUTDOWN_TASK");
      disconnect_neighbour (neighbours, GNUNET_NO);
    }
#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Transport service is unloading plugins...\n");
#endif
  while (NULL != (plug = plugins))
    {
      plugins = plug->next;
      if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
	{
	  GNUNET_SCHEDULER_cancel (plug->address_update_task);
	  plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
	}
      GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
      GNUNET_free (plug->lib_name);
      GNUNET_free (plug->short_name);
      while (NULL != (al = plug->addresses))
        {
          plug->addresses = al->next;
          GNUNET_free (al);
        }
      GNUNET_free (plug);
    }
  if (my_private_key != NULL)
    GNUNET_CRYPTO_rsa_key_free (my_private_key);
  GNUNET_free_non_null (our_hello);

  GNUNET_CONTAINER_multihashmap_iterate (validation_map,
					 &abort_validation,
					 NULL);
  GNUNET_CONTAINER_multihashmap_destroy (validation_map);
  validation_map = NULL;

  /* free 'chvc' data structure */
  while (NULL != (chvc = chvc_head))
    {
      chvc_head = chvc->next;
      if (chvc->piter != NULL)
        {
          GNUNET_PEERINFO_iterate_cancel (chvc->piter);
          GNUNET_STATISTICS_update (stats,
                                    gettext_noop ("# outstanding peerinfo iterate requests"),
                                    -1,
                                    GNUNET_NO);
        }
      else
	GNUNET_break (0);
      GNUNET_assert (chvc->ve_count == 0);
      GNUNET_free (chvc);
    }
  chvc_tail = NULL;

  if (stats != NULL)
    {
      GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
      stats = NULL;
    }
  if (peerinfo != NULL)
    {
      GNUNET_PEERINFO_disconnect (peerinfo);
      peerinfo = NULL;
    }
  /* Can we assume those are gone by now, or do we need to clean up
     explicitly!? */
  GNUNET_break (bl_head == NULL);
  GNUNET_break (bc_head == NULL);
}


/**
 * Initiate transport service.
 *
 * @param cls closure
 * @param server the initialized server
 * @param c configuration to use
 */
static void
run (void *cls,
     struct GNUNET_SERVER_Handle *server,
     const struct GNUNET_CONFIGURATION_Handle *c)
{
  static const struct GNUNET_SERVER_MessageHandler handlers[] = {
    {&handle_start, NULL,
     GNUNET_MESSAGE_TYPE_TRANSPORT_START, sizeof (struct StartMessage)},
    {&handle_hello, NULL,
     GNUNET_MESSAGE_TYPE_HELLO, 0},
    {&handle_send, NULL,
     GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
    {&handle_request_connect, NULL,
     GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT, sizeof(struct TransportRequestConnectMessage)},
    {&handle_set_quota, NULL,
     GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
    {&handle_address_lookup, NULL,
     GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
     0},
    {&handle_blacklist_init, NULL,
     GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
    {&handle_blacklist_reply, NULL,
     GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
    {NULL, NULL, 0, 0}
  };
  char *plugs;
  char *pos;
  int no_transports;
  unsigned long long tneigh;
  char *keyfile;

  cfg = c;
  stats = GNUNET_STATISTICS_create ("transport", cfg);
  validation_map = GNUNET_CONTAINER_multihashmap_create (64);
  /* parse configuration */
  if ((GNUNET_OK !=
       GNUNET_CONFIGURATION_get_value_number (c,
                                              "TRANSPORT",
                                              "NEIGHBOUR_LIMIT",
                                              &tneigh)) ||
      (GNUNET_OK !=
       GNUNET_CONFIGURATION_get_value_filename (c,
                                                "GNUNETD",
                                                "HOSTKEY", &keyfile)))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  _
                  ("Transport service is lacking key configuration settings.  Exiting.\n"));
      GNUNET_SCHEDULER_shutdown ();
      if (stats != NULL)
	{
	  GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
	  stats = NULL;
	}
      GNUNET_CONTAINER_multihashmap_destroy (validation_map);
      validation_map = NULL;
      return;
    }
  max_connect_per_transport = (uint32_t) tneigh;
  peerinfo = GNUNET_PEERINFO_connect (cfg);
  if (peerinfo == NULL)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		  _("Could not access PEERINFO service.  Exiting.\n"));	
      GNUNET_SCHEDULER_shutdown ();
      if (stats != NULL)
	{
	  GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
	  stats = NULL;
	}
      GNUNET_CONTAINER_multihashmap_destroy (validation_map);
      validation_map = NULL;
      GNUNET_free (keyfile);
      return;
    }
  my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
  GNUNET_free (keyfile);
  if (my_private_key == NULL)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  _
                  ("Transport service could not access hostkey.  Exiting.\n"));
      GNUNET_SCHEDULER_shutdown ();
      if (stats != NULL)
	{
	  GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
	  stats = NULL;
	}
      GNUNET_CONTAINER_multihashmap_destroy (validation_map);
      validation_map = NULL;
      return;
    }
  GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
  GNUNET_CRYPTO_hash (&my_public_key,
                      sizeof (my_public_key), &my_identity.hashPubKey);
  /* setup notification */
  GNUNET_SERVER_disconnect_notify (server,
                                   &client_disconnect_notification, NULL);
  /* load plugins... */
  no_transports = 1;
  if (GNUNET_OK ==
      GNUNET_CONFIGURATION_get_value_string (c,
                                             "TRANSPORT", "PLUGINS", &plugs))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  _("Starting transport plugins `%s'\n"), plugs);
      pos = strtok (plugs, " ");
      while (pos != NULL)
        {
          start_transport (server, pos);
          no_transports = 0;
          pos = strtok (NULL, " ");
        }
      GNUNET_free (plugs);
    }
  GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
                                &shutdown_task, NULL);
  if (no_transports)
    refresh_hello ();

#if DEBUG_TRANSPORT
  GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
#endif
  /* If we have a blacklist file, read from it */
  read_blacklist_file(cfg);
  /* process client requests */
  GNUNET_SERVER_add_handlers (server, handlers);
}


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

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