summaryrefslogtreecommitdiff
path: root/src/cadet/gnunet-service-cadet_connection.c
blob: b82c788e9df4ab4e83cdf0d0543e018f86a44fce (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
/*
     This file is part of GNUnet.
     Copyright (C) 2001-2015 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., 51 Franklin Street, Fifth Floor,
     Boston, MA 02110-1301, USA.
*/
/**
 * @file cadet/gnunet-service-cadet_connection.c
 * @brief GNUnet CADET service connection handling
 * @author Bartlomiej Polot
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_statistics_service.h"
#include "cadet_path.h"
#include "cadet_protocol.h"
#include "cadet.h"
#include "gnunet-service-cadet_connection.h"
#include "gnunet-service-cadet_peer.h"
#include "gnunet-service-cadet_tunnel.h"


/**
 * Should we run somewhat expensive checks on our invariants?
 */
#define CHECK_INVARIANTS 0


#define LOG(level, ...) GNUNET_log_from (level,"cadet-con",__VA_ARGS__)
#define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-con",__VA_ARGS__)


#define CADET_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
                                  GNUNET_TIME_UNIT_MINUTES,\
                                  10)
#define AVG_MSGS                32


/******************************************************************************/
/********************************   STRUCTS  **********************************/
/******************************************************************************/

/**
 * Struct to encapsulate all the Flow Control information to a peer to which
 * we are directly connected (on a core level).
 */
struct CadetFlowControl
{
  /**
   * Connection this controls.
   */
  struct CadetConnection *c;

  /**
   * How many messages are in the queue on this connection.
   */
  unsigned int queue_n;

  /**
   * How many messages do we accept in the queue.
   */
  unsigned int queue_max;

  /**
   * ID of the last packet sent towards the peer.
   */
  uint32_t last_pid_sent;

  /**
   * ID of the last packet received from the peer.
   */
  uint32_t last_pid_recv;

  /**
   * Bitmap of past 32 messages received:
   * - LSB being @c last_pid_recv.
   * - MSB being @c last_pid_recv - 31 (mod UINTMAX).
   */
  uint32_t recv_bitmap;

  /**
   * Last ACK sent to the peer (peer can't send more than this PID).
   */
  uint32_t last_ack_sent;

  /**
   * Last ACK sent towards the origin (for traffic towards leaf node).
   */
  uint32_t last_ack_recv;

  /**
   * Task to poll the peer in case of a lost ACK causes stall.
   */
  struct GNUNET_SCHEDULER_Task *poll_task;

  /**
   * How frequently to poll for ACKs.
   */
  struct GNUNET_TIME_Relative poll_time;

  /**
   * Queued poll message, to cancel if not necessary anymore (got ACK).
   */
  struct CadetConnectionQueue *poll_msg;

  /**
   * Queued poll message, to cancel if not necessary anymore (got ACK).
   */
  struct CadetConnectionQueue *ack_msg;
};

/**
 * Keep a record of the last messages sent on this connection.
 */
struct CadetConnectionPerformance
{
  /**
   * Circular buffer for storing measurements.
   */
  double usecsperbyte[AVG_MSGS];

  /**
   * Running average of @c usecsperbyte.
   */
  double avg;

  /**
   * How many values of @c usecsperbyte are valid.
   */
  uint16_t size;

  /**
   * Index of the next "free" position in @c usecsperbyte.
   */
  uint16_t idx;
};


/**
 * Struct containing all information regarding a connection to a peer.
 */
struct CadetConnection
{
  /**
   * Tunnel this connection is part of.
   */
  struct CadetTunnel *t;

  /**
   * Flow control information for traffic fwd.
   */
  struct CadetFlowControl fwd_fc;

  /**
   * Flow control information for traffic bck.
   */
  struct CadetFlowControl bck_fc;

  /**
   * Measure connection performance on the endpoint.
   */
  struct CadetConnectionPerformance *perf;

  /**
   * ID of the connection.
   */
  struct GNUNET_CADET_Hash id;

  /**
   * Path being used for the tunnel. At the origin of the connection
   * it's a pointer to the destination's path pool, otherwise just a copy.
   */
  struct CadetPeerPath *path;

  /**
   * Task to keep the used paths alive at the owner,
   * time tunnel out on all the other peers.
   */
  struct GNUNET_SCHEDULER_Task *fwd_maintenance_task;

  /**
   * Task to keep the used paths alive at the destination,
   * time tunnel out on all the other peers.
   */
  struct GNUNET_SCHEDULER_Task *bck_maintenance_task;

  /**
   * Queue handle for maintainance traffic. One handle for FWD and BCK since
   * one peer never needs to maintain both directions (no loopback connections).
   */
  struct CadetPeerQueue *maintenance_q;

  /**
   * Should equal #get_next_hop(), or NULL if that peer disconnected.
   */
  struct CadetPeer *next_peer;

  /**
   * Should equal #get_prev_hop(), or NULL if that peer disconnected.
   */
  struct CadetPeer *prev_peer;

  /**
   * State of the connection.
   */
  enum CadetConnectionState state;

  /**
   * Position of the local peer in the path.
   */
  unsigned int own_pos;

  /**
   * Pending message count.
   */
  unsigned int pending_messages;

  /**
   * Destroy flag:
   * - if 0, connection in use.
   * - if 1, destroy on last message.
   * - if 2, connection is being destroyed don't re-enter.
   */
  int destroy;

  /**
   * In-connection-map flag. Sometimes, when @e destroy is set but
   * actual destruction is delayed to enable us to finish processing
   * queues (i.e. in the direction that is still working), we remove
   * the connection from the map to prevent it from still being
   * found (and used) by accident. This flag is set to #GNUNET_YES
   * for a connection that is not in the #connections map.  Should
   * only be #GNUNET_YES if #destroy is also non-zero.
   */
  int was_removed;

  /**
   * Counter to do exponential backoff when creating a connection (max 64).
   */
  unsigned short create_retry;

  /**
   * Task to check if connection has duplicates.
   */
  struct GNUNET_SCHEDULER_Task *check_duplicates_task;
};


/**
 * Handle for messages queued but not yet sent.
 */
struct CadetConnectionQueue
{
  /**
   * Peer queue handle, to cancel if necessary.
   */
  struct CadetPeerQueue *q;

  /**
   * Continuation to call once sent.
   */
  GCC_sent cont;

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

  /**
   * Was this a forced message? (Do not account for it)
   */
  int forced;
};

/******************************************************************************/
/*******************************   GLOBALS  ***********************************/
/******************************************************************************/

/**
 * Global handle to the statistics service.
 */
extern struct GNUNET_STATISTICS_Handle *stats;

/**
 * Local peer own ID (memory efficient handle).
 */
extern GNUNET_PEER_Id myid;

/**
 * Local peer own ID (full value).
 */
extern struct GNUNET_PeerIdentity my_full_id;

/**
 * Connections known, indexed by cid (CadetConnection).
 */
static struct GNUNET_CONTAINER_MultiHashMap *connections;

/**
 * How many connections are we willing to maintain.
 * Local connections are always allowed, even if there are more connections than max.
 */
static unsigned long long max_connections;

/**
 * How many messages *in total* are we willing to queue, divide by number of
 * connections to get connection queue size.
 */
static unsigned long long max_msgs_queue;

/**
 * How often to send path keepalives. Paths timeout after 4 missed.
 */
static struct GNUNET_TIME_Relative refresh_connection_time;

/**
 * How often to send path create / ACKs.
 */
static struct GNUNET_TIME_Relative create_connection_time;


/******************************************************************************/
/********************************   STATIC  ***********************************/
/******************************************************************************/



#if 0 // avoid compiler warning for unused static function
static void
fc_debug (struct CadetFlowControl *fc)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG, "    IN: %u/%u\n",
              fc->last_pid_recv, fc->last_ack_sent);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "    OUT: %u/%u\n",
              fc->last_pid_sent, fc->last_ack_recv);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "    QUEUE: %u/%u\n",
              fc->queue_n, fc->queue_max);
}

static void
connection_debug (struct CadetConnection *c)
{
  if (NULL == c)
  {
    LOG (GNUNET_ERROR_TYPE_INFO, "DEBUG NULL CONNECTION\n");
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s:%X\n",
              peer2s (c->t->peer), GCC_2s (c));
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  state: %u, pending msgs: %u\n",
              c->state, c->pending_messages);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
  fc_debug (&c->fwd_fc);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
  fc_debug (&c->bck_fc);
}
#endif


/**
 * Schedule next keepalive task, taking in consideration
 * the connection state and number of retries.
 *
 * @param c Connection for which to schedule the next keepalive.
 * @param fwd Direction for the next keepalive.
 */
static void
schedule_next_keepalive (struct CadetConnection *c, int fwd);


/**
 * Resets the connection timeout task, some other message has done the
 * task's job.
 * - For the first peer on the direction this means to send
 *   a keepalive or a path confirmation message (either create or ACK).
 * - For all other peers, this means to destroy the connection,
 *   due to lack of activity.
 * Starts the timeout if no timeout was running (connection just created).
 *
 * @param c Connection whose timeout to reset.
 * @param fwd Is this forward?
 */
static void
connection_reset_timeout (struct CadetConnection *c, int fwd);


/**
 * Get string description for tunnel state. Reentrant.
 *
 * @param s Tunnel state.
 *
 * @return String representation.
 */
static const char *
GCC_state2s (enum CadetConnectionState s)
{
  switch (s)
  {
    case CADET_CONNECTION_NEW:
      return "CADET_CONNECTION_NEW";
    case CADET_CONNECTION_SENT:
      return "CADET_CONNECTION_SENT";
    case CADET_CONNECTION_ACK:
      return "CADET_CONNECTION_ACK";
    case CADET_CONNECTION_READY:
      return "CADET_CONNECTION_READY";
    case CADET_CONNECTION_DESTROYED:
      return "CADET_CONNECTION_DESTROYED";
    case CADET_CONNECTION_BROKEN:
      return "CADET_CONNECTION_BROKEN";
    default:
      GNUNET_break (0);
      LOG (GNUNET_ERROR_TYPE_ERROR, " conn state %u unknown!\n", s);
      return "CADET_CONNECTION_STATE_ERROR";
  }
}


/**
 * Initialize a Flow Control structure to the initial state.
 *
 * @param fc Flow Control structure to initialize.
 */
static void
fc_init (struct CadetFlowControl *fc)
{
  fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
  fc->last_pid_recv = (uint32_t) -1;
  fc->last_ack_sent = (uint32_t) 0;
  fc->last_ack_recv = (uint32_t) 0;
  fc->poll_task = NULL;
  fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
  fc->queue_n = 0;
  fc->queue_max = (max_msgs_queue / max_connections) + 1;
}


/**
 * Find a connection.
 *
 * @param cid Connection ID.
 */
static struct CadetConnection *
connection_get (const struct GNUNET_CADET_Hash *cid)
{
  return GNUNET_CONTAINER_multihashmap_get (connections, GC_h2hc (cid));
}


static void
connection_change_state (struct CadetConnection* c,
                         enum CadetConnectionState state)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Connection %s state %s -> %s\n",
       GCC_2s (c), GCC_state2s (c->state), GCC_state2s (state));
  if (CADET_CONNECTION_DESTROYED <= c->state) /* Destroyed or broken. */
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "state not changing anymore\n");
    return;
  }
  c->state = state;
  if (CADET_CONNECTION_READY == state)
    c->create_retry = 1;
}


/**
 * Callback called when a queued ACK message is sent.
 *
 * @param cls Closure (FC).
 * @param c Connection this message was on.
 * @param q Queue handler this call invalidates.
 * @param type Type of message sent.
 * @param fwd Was this a FWD going message?
 * @param size Size of the message.
 */
static void
ack_sent (void *cls,
          struct CadetConnection *c,
          struct CadetConnectionQueue *q,
          uint16_t type, int fwd, size_t size)
{
  struct CadetFlowControl *fc = cls;

  fc->ack_msg = NULL;
}


/**
 * Send an ACK on the connection, informing the predecessor about
 * the available buffer space. Should not be called in case the peer
 * is origin (no predecessor) in the @c fwd direction.
 *
 * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
 * the ACK itself goes "back" (dest->root).
 *
 * @param c Connection on which to send the ACK.
 * @param buffer How much space free to advertise?
 * @param fwd Is this FWD ACK? (Going dest -> root)
 * @param force Don't optimize out.
 */
static void
send_ack (struct CadetConnection *c, unsigned int buffer, int fwd, int force)
{
  struct CadetFlowControl *next_fc;
  struct CadetFlowControl *prev_fc;
  struct GNUNET_CADET_ACK msg;
  uint32_t ack;
  int delta;

  /* If origin, there is no connection to send ACKs. Wrong function! */
  GCC_check_connections ();
  if (GCC_is_origin (c, fwd))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "connection %s is origin in %s\n",
         GCC_2s (c), GC_f2s (fwd));
    GNUNET_break (0);
    return;
  }

  next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
  prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "connection send %s ack on %s\n",
       GC_f2s (fwd), GCC_2s (c));

  /* Check if we need to transmit the ACK. */
  delta = prev_fc->last_ack_sent - prev_fc->last_pid_recv;
  if (3 < delta && buffer < delta && GNUNET_NO == force)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "  last pid recv: %u, last ack sent: %u\n",
         prev_fc->last_pid_recv, prev_fc->last_ack_sent);
    GCC_check_connections ();
    return;
  }

  /* Ok, ACK might be necessary, what PID to ACK? */
  ack = prev_fc->last_pid_recv + buffer;
  LOG (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       " last pid %u, last ack %u, qmax %u, q %u\n",
       prev_fc->last_pid_recv, prev_fc->last_ack_sent,
       next_fc->queue_max, next_fc->queue_n);
  if (ack == prev_fc->last_ack_sent && GNUNET_NO == force)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
    GCC_check_connections ();
    return;
  }

  /* Check if message is already in queue */
  if (NULL != prev_fc->ack_msg)
  {
    if (GC_is_pid_bigger (ack, prev_fc->last_ack_sent))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, " canceling old ACK\n");
      GCC_cancel (prev_fc->ack_msg);
      /* GCC_cancel triggers ack_sent(), which clears fc->ack_msg */
    }
    else
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, " same ACK already in queue\n");
      GCC_check_connections ();
      return;
    }
  }

  prev_fc->last_ack_sent = ack;

  /* Build ACK message and send on conn */
  msg.header.size = htons (sizeof (msg));
  msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ACK);
  msg.ack = htonl (ack);
  msg.cid = c->id;

  prev_fc->ack_msg = GCC_send_prebuilt_message (&msg.header, 0, ack, c,
                                                !fwd, GNUNET_YES,
                                                &ack_sent, prev_fc);
  GNUNET_assert (NULL != prev_fc->ack_msg);
  GCC_check_connections ();
}


/**
 * Callback called when a connection queued message is sent.
 *
 * Calculates the average time and connection packet tracking.
 *
 * @param cls Closure (ConnectionQueue Handle).
 * @param c Connection this message was on.
 * @param sent Was it really sent? (Could have been canceled)
 * @param type Type of message sent.
 * @param pid Packet ID, or 0 if not applicable (create, destroy, etc).
 * @param fwd Was this a FWD going message?
 * @param size Size of the message.
 * @param wait Time spent waiting for core (only the time for THIS message)
 * @return #GNUNET_YES if connection was destroyed, #GNUNET_NO otherwise.
 */
static int
conn_message_sent (void *cls,
                   struct CadetConnection *c, int sent,
                   uint16_t type, uint32_t pid, int fwd, size_t size,
                   struct GNUNET_TIME_Relative wait)
{
  struct CadetConnectionPerformance *p;
  struct CadetFlowControl *fc;
  struct CadetConnectionQueue *q = cls;
  double usecsperbyte;
  int forced;

  GCC_check_connections ();
  LOG (GNUNET_ERROR_TYPE_DEBUG, "connection message_sent\n");

  GCC_debug (c, GNUNET_ERROR_TYPE_DEBUG);

  fc = fwd ? &c->fwd_fc : &c->bck_fc;
  LOG (GNUNET_ERROR_TYPE_DEBUG, " %ssent %s %s pid %u\n",
       sent ? "" : "not ", GC_f2s (fwd), GC_m2s (type), pid);
  if (NULL != q)
  {
    forced = q->forced;
    if (NULL != q->cont)
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, " calling cont\n");
      q->cont (q->cont_cls, c, q, type, fwd, size);
    }
    GNUNET_free (q);
  }
  else if (type == GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED
           || type == GNUNET_MESSAGE_TYPE_CADET_AX)
  {
    /* If NULL == q and ENCRYPTED == type, message must have been ch_mngmnt */
    forced = GNUNET_YES;
  }
  else
  {
    forced = GNUNET_NO;
  }
  if (NULL == c)
  {
    if (type != GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN
        && type != GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY)
    {
      LOG (GNUNET_ERROR_TYPE_ERROR, "Message %s sent on NULL connection!\n",
           GC_m2s (type));
    }
    GCC_check_connections ();
    return GNUNET_NO;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, " C_P- %p %u\n", c, c->pending_messages);
  c->pending_messages--;
  if ( (GNUNET_YES == c->destroy) &&
       (0 == c->pending_messages) )
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "!  destroying connection!\n");
    GCC_destroy (c);
    GCC_check_connections ();
    return GNUNET_YES;
  }
  /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
  switch (type)
  {
    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
      c->maintenance_q = NULL;
      /* Don't trigger a keepalive for sent ACKs, only SYN and SYNACKs */
      if (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE == type || !fwd)
        schedule_next_keepalive (c, fwd);
      break;

    case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
    case GNUNET_MESSAGE_TYPE_CADET_AX:
      if (GNUNET_YES == sent)
      {
        GNUNET_assert (NULL != q);
        fc->last_pid_sent = pid;
        if (GC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
          GCC_start_poll (c, fwd);
        GCC_send_ack (c, fwd, GNUNET_NO);
        connection_reset_timeout (c, fwd);
      }

      LOG (GNUNET_ERROR_TYPE_DEBUG, "!  Q_N- %p %u\n", fc, fc->queue_n);
      if (GNUNET_NO == forced)
      {
        fc->queue_n--;
        LOG (GNUNET_ERROR_TYPE_DEBUG,
            "!   accounting pid %u\n",
            fc->last_pid_sent);
      }
      else
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG,
             "!   forced, Q_N not accounting pid %u\n",
             fc->last_pid_sent);
      }
      break;

    case GNUNET_MESSAGE_TYPE_CADET_KX:
      if (GNUNET_YES == sent)
        connection_reset_timeout (c, fwd);
      break;

    case GNUNET_MESSAGE_TYPE_CADET_POLL:
      fc->poll_msg = NULL;
      break;

    case GNUNET_MESSAGE_TYPE_CADET_ACK:
      fc->ack_msg = NULL;
      break;

    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
      break;

    default:
      LOG (GNUNET_ERROR_TYPE_ERROR, "%s unknown\n", GC_m2s (type));
      GNUNET_break (0);
      break;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, "!  message sent!\n");

  if (NULL == c->perf)
    return GNUNET_NO; /* Only endpoints are interested in timing. */

  p = c->perf;
  usecsperbyte = ((double) wait.rel_value_us) / size;
  if (p->size == AVG_MSGS)
  {
    /* Array is full. Substract oldest value, add new one and store. */
    p->avg -= (p->usecsperbyte[p->idx] / AVG_MSGS);
    p->usecsperbyte[p->idx] = usecsperbyte;
    p->avg += (p->usecsperbyte[p->idx] / AVG_MSGS);
  }
  else
  {
    /* Array not yet full. Add current value to avg and store. */
    p->usecsperbyte[p->idx] = usecsperbyte;
    p->avg *= p->size;
    p->avg += p->usecsperbyte[p->idx];
    p->size++;
    p->avg /= p->size;
  }
  p->idx = (p->idx + 1) % AVG_MSGS;
  GCC_check_connections ();
  return GNUNET_NO;
}


/**
 * Get the previous hop in a connection
 *
 * @param c Connection.
 *
 * @return Previous peer in the connection.
 */
static struct CadetPeer *
get_prev_hop (const struct CadetConnection *c)
{
  GNUNET_PEER_Id id;

  if (NULL == c->path)
    return NULL;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       " get prev hop %s [%u/%u]\n",
       GCC_2s (c), c->own_pos, c->path->length);
  if (0 == c->own_pos || c->path->length < 2)
    id = c->path->peers[0];
  else
    id = c->path->peers[c->own_pos - 1];

  LOG (GNUNET_ERROR_TYPE_DEBUG, "  ID: %s (%u)\n",
       GNUNET_i2s (GNUNET_PEER_resolve2 (id)), id);

  return GCP_get_short (id, GNUNET_YES);
}


/**
 * Get the next hop in a connection
 *
 * @param c Connection.
 *
 * @return Next peer in the connection.
 */
static struct CadetPeer *
get_next_hop (const struct CadetConnection *c)
{
  GNUNET_PEER_Id id;

  if (NULL == c->path)
    return NULL;

  LOG (GNUNET_ERROR_TYPE_DEBUG, " get next hop %s [%u/%u]\n",
       GCC_2s (c), c->own_pos, c->path->length);
  if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
    id = c->path->peers[c->path->length - 1];
  else
    id = c->path->peers[c->own_pos + 1];

  LOG (GNUNET_ERROR_TYPE_DEBUG, "  ID: %s (%u)\n",
       GNUNET_i2s (GNUNET_PEER_resolve2 (id)), id);

  return GCP_get_short (id, GNUNET_YES);
}


/**
 * Check that the direct neighbours (previous and next hop)
 * are properly associated with this connection.
 *
 * @param c connection to check
 */
static void
check_neighbours (const struct CadetConnection *c)
{
  if (NULL == c->path)
    return; /* nothing to check */
  GCP_check_connection (get_next_hop (c), c);
  GCP_check_connection (get_prev_hop (c), c);
}


/**
 * Helper for #check_connections().  Calls #check_neighbours().
 *
 * @param cls NULL
 * @param key ignored
 * @param value the `struct CadetConnection` to check
 * @return #GNUNET_OK (continue to iterate)
 */
static int
check_connection (void *cls,
                  const struct GNUNET_HashCode *key,
                  void *value)
{
  struct CadetConnection *c = value;

  check_neighbours (c);
  return GNUNET_OK;
}


/**
 * Check invariants for all connections using #check_neighbours().
 */
void
GCC_check_connections ()
{
  if (0 == CHECK_INVARIANTS)
    return;
  if (NULL == connections)
    return;
  GNUNET_CONTAINER_multihashmap_iterate (connections,
                                         &check_connection,
                                         NULL);
}


/**
 * Get the hop in a connection.
 *
 * @param c Connection.
 * @param fwd Next in the FWD direction?
 *
 * @return Next peer in the connection.
 */
static struct CadetPeer *
get_hop (struct CadetConnection *c, int fwd)
{
  return (fwd) ? get_next_hop (c) : get_prev_hop (c);
}


/**
 * Get a bit mask for a message received out-of-order.
 *
 * @param last_pid_recv Last PID we received prior to the out-of-order.
 * @param ooo_pid PID of the out-of-order message.
 */
static uint32_t
get_recv_bitmask (uint32_t last_pid_recv, uint32_t ooo_pid)
{
  return 1 << (last_pid_recv - ooo_pid);
}


/**
 * Check is an out-of-order message is ok:
 * - at most 31 messages behind.
 * - not duplicate.
 *
 * @param last_pid_recv Last in-order PID received.
 */
static int
is_ooo_ok (uint32_t last_pid_recv, uint32_t ooo_pid, uint32_t ooo_bitmap)
{
  uint32_t mask;

  if (GC_is_pid_bigger (last_pid_recv - 31, ooo_pid))
    return GNUNET_NO;

  mask = get_recv_bitmask (last_pid_recv, ooo_pid);
  if (0 != (ooo_bitmap & mask))
    return GNUNET_NO;

  return GNUNET_YES;
}


/**
 * Is traffic coming from this sender 'FWD' traffic?
 *
 * @param c Connection to check.
 * @param sender Peer identity of neighbor.
 *
 * @return #GNUNET_YES in case the sender is the 'prev' hop and therefore
 *         the traffic is 'FWD'.
 *         #GNUNET_NO for BCK.
 *         #GNUNET_SYSERR for errors.
 */
static int
is_fwd (const struct CadetConnection *c,
        const struct GNUNET_PeerIdentity *sender)
{
  GNUNET_PEER_Id id;

  id = GNUNET_PEER_search (sender);
  if (GCP_get_short_id (get_prev_hop (c)) == id)
    return GNUNET_YES;

  if (GCP_get_short_id (get_next_hop (c)) == id)
    return GNUNET_NO;

  GNUNET_break (0);
  return GNUNET_SYSERR;
}


/**
 * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
 * or a first CONNECTION_ACK directed to us.
 *
 * @param connection Connection to confirm.
 * @param fwd Should we send it FWD? (root->dest)
 *            (First (~SYNACK) goes BCK, second (~ACK) goes FWD)
 */
static void
send_connection_ack (struct CadetConnection *connection, int fwd)
{
  struct CadetTunnel *t;

  GCC_check_connections ();
  t = connection->t;
  LOG (GNUNET_ERROR_TYPE_INFO, "--> {%14s ACK} on conn %s\n",
       GC_f2s (!fwd), GCC_2s (connection));
  GCP_queue_add (get_hop (connection, fwd), NULL,
                 GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK, 0, 0,
                 sizeof (struct GNUNET_CADET_ConnectionACK),
                 connection, fwd, &conn_message_sent, NULL);
  connection->pending_messages++;
  if (CADET_TUNNEL_NEW == GCT_get_cstate (t))
    GCT_change_cstate (t, CADET_TUNNEL_WAITING);
  if (CADET_CONNECTION_READY != connection->state)
    connection_change_state (connection, CADET_CONNECTION_SENT);
  GCC_check_connections ();
}


/**
 * Send a notification that a connection is broken.
 *
 * @param c Connection that is broken.
 * @param id1 Peer that has disconnected.
 * @param id2 Peer that has disconnected.
 * @param fwd Direction towards which to send it.
 */
static void
send_broken (struct CadetConnection *c,
             const struct GNUNET_PeerIdentity *id1,
             const struct GNUNET_PeerIdentity *id2,
             int fwd)
{
  struct GNUNET_CADET_ConnectionBroken msg;

  GCC_check_connections ();
  msg.header.size = htons (sizeof (struct GNUNET_CADET_ConnectionBroken));
  msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN);
  msg.cid = c->id;
  msg.peer1 = *id1;
  msg.peer2 = *id2;
  GNUNET_assert (NULL ==
                 GCC_send_prebuilt_message (&msg.header, 0, 0, c, fwd,
                                            GNUNET_YES, NULL, NULL));
  GCC_check_connections ();
}


/**
 * Send a notification that a connection is broken, when a connection
 * isn't even known to the local peer or soon to be destroyed.
 *
 * @param connection_id Connection ID.
 * @param id1 Peer that has disconnected, probably local peer.
 * @param id2 Peer that has disconnected can be NULL if unknown.
 * @param peer Peer to notify (neighbor who sent the connection).
 */
static void
send_broken_unknown (const struct GNUNET_CADET_Hash *connection_id,
                     const struct GNUNET_PeerIdentity *id1,
                     const struct GNUNET_PeerIdentity *id2,
                     const struct GNUNET_PeerIdentity *peer_id)
{
  struct GNUNET_CADET_ConnectionBroken *msg;
  struct CadetPeer *neighbor;

  GCC_check_connections ();
  LOG (GNUNET_ERROR_TYPE_INFO, "--> BROKEN on unknown connection %s\n",
       GNUNET_h2s (GC_h2hc (connection_id)));

  msg = GNUNET_new (struct GNUNET_CADET_ConnectionBroken);
  msg->header.size = htons (sizeof (struct GNUNET_CADET_ConnectionBroken));
  msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN);
  msg->cid = *connection_id;
  msg->peer1 = *id1;
  if (NULL != id2)
    msg->peer2 = *id2;
  else
    memset (&msg->peer2, 0, sizeof (msg->peer2));
  neighbor = GCP_get (peer_id, GNUNET_NO); /* We MUST know neighbor. */
  GNUNET_assert (NULL != neighbor);
  GCP_queue_add (neighbor, msg, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN,
                 0, 2, sizeof (struct GNUNET_CADET_ConnectionBroken),
                 NULL, GNUNET_SYSERR, /* connection, fwd */
                 NULL, NULL); /* continuation */
  GCC_check_connections ();
}


/**
 * Send keepalive packets for a connection.
 *
 * @param c Connection to keep alive..
 * @param fwd Is this a FWD keepalive? (owner -> dest).
 */
static void
send_connection_keepalive (struct CadetConnection *c, int fwd)
{
  struct GNUNET_MessageHeader msg;
  struct CadetFlowControl *fc;

  GCC_check_connections ();
  LOG (GNUNET_ERROR_TYPE_INFO,
       "keepalive %s for connection %s\n",
       GC_f2s (fwd), GCC_2s (c));

  GNUNET_assert (NULL != c->t);
  fc = fwd ? &c->fwd_fc : &c->bck_fc;
  if (0 < fc->queue_n || GNUNET_YES == GCT_has_queued_traffic (c->t))
  {
    LOG (GNUNET_ERROR_TYPE_INFO, "not sending keepalive, traffic in queue\n");
    return;
  }

  GNUNET_STATISTICS_update (stats, "# keepalives sent", 1, GNUNET_NO);

  GNUNET_assert (NULL != c->t);
  msg.size = htons (sizeof (msg));
  msg.type = htons (GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE);

  GNUNET_assert (NULL ==
                 GCT_send_prebuilt_message (&msg, c->t, c,
                                            GNUNET_NO, NULL, NULL));
  GCC_check_connections ();
}


/**
 * Send CONNECTION_{CREATE/ACK} packets for a connection.
 *
 * @param c Connection for which to send the message.
 * @param fwd If #GNUNET_YES, send CREATE, otherwise send ACK.
 */
static void
connection_recreate (struct CadetConnection *c, int fwd)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "sending connection recreate\n");
  if (fwd)
    GCC_send_create (c);
  else
    send_connection_ack (c, GNUNET_NO);
}


/**
 * Generic connection timer management.
 * Depending on the role of the peer in the connection will send the
 * appropriate message (build or keepalive)
 *
 * @param c Conncetion to maintain.
 * @param fwd Is FWD?
 */
static void
connection_maintain (struct CadetConnection *c, int fwd)
{
  if (GNUNET_NO != c->destroy)
  {
    LOG (GNUNET_ERROR_TYPE_INFO, "not sending keepalive, being destroyed\n");
    return;
  }

  if (NULL == c->t)
  {
    GNUNET_break (0);
    GCC_debug (c, GNUNET_ERROR_TYPE_ERROR);
    return;
  }

  if (CADET_TUNNEL_SEARCHING == GCT_get_cstate (c->t))
  {
    /* If status is SEARCHING, why is there a connection? Should be WAITING */
    GNUNET_break (0);
    GCT_debug (c->t, GNUNET_ERROR_TYPE_ERROR);
    LOG (GNUNET_ERROR_TYPE_INFO, "not sending keepalive, tunnel SEARCHING\n");
    schedule_next_keepalive (c, fwd);
    return;
  }
  switch (c->state)
  {
    case CADET_CONNECTION_NEW:
      GNUNET_break (0);
      /* fall-through */
    case CADET_CONNECTION_SENT:
      connection_recreate (c, fwd);
      break;
    case CADET_CONNECTION_READY:
      send_connection_keepalive (c, fwd);
      break;
    default:
      break;
  }
}


/**
 * Keep the connection alive.
 *
 * @param c Connection to keep alive.
 * @param fwd Direction.
 * @param shutdown Are we shutting down? (Don't send traffic)
 *                 Non-zero value for true, not necessarily GNUNET_YES.
 */
static void
connection_keepalive (struct CadetConnection *c, int fwd, int shutdown)
{
  GCC_check_connections ();
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s keepalive for %s\n",
       GC_f2s (fwd), GCC_2s (c));

  if (fwd)
    c->fwd_maintenance_task = NULL;
  else
    c->bck_maintenance_task = NULL;

  if (GNUNET_NO != shutdown)
    return;

  connection_maintain (c, fwd);
  GCC_check_connections ();
  /* Next execution will be scheduled by message_sent or _maintain*/
}


/**
 * Keep the connection alive in the FWD direction.
 *
 * @param cls Closure (connection to keepalive).
 * @param tc TaskContext.
 */
static void
connection_fwd_keepalive (void *cls,
                          const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  GCC_check_connections ();
  connection_keepalive ((struct CadetConnection *) cls,
                        GNUNET_YES,
                        tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN);
  GCC_check_connections ();
}


/**
 * Keep the connection alive in the BCK direction.
 *
 * @param cls Closure (connection to keepalive).
 * @param tc TaskContext.
 */
static void
connection_bck_keepalive (void *cls,
                          const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  GCC_check_connections ();
  connection_keepalive ((struct CadetConnection *) cls,
                        GNUNET_NO,
                        tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN);
  GCC_check_connections ();
}


/**
 * Schedule next keepalive task, taking in consideration
 * the connection state and number of retries.
 *
 * If the peer is not the origin, do nothing.
 *
 * @param c Connection for which to schedule the next keepalive.
 * @param fwd Direction for the next keepalive.
 */
static void
schedule_next_keepalive (struct CadetConnection *c, int fwd)
{
  struct GNUNET_TIME_Relative delay;
  struct GNUNET_SCHEDULER_Task * *task_id;
  GNUNET_SCHEDULER_TaskCallback keepalive_task;

  GCC_check_connections ();
  if (GNUNET_NO == GCC_is_origin (c, fwd))
    return;

  /* Calculate delay to use, depending on the state of the connection */
  if (CADET_CONNECTION_READY == c->state)
  {
    delay = refresh_connection_time;
  }
  else
  {
    if (1 > c->create_retry)
      c->create_retry = 1;
    delay = GNUNET_TIME_relative_multiply (create_connection_time,
                                           c->create_retry);
    if (c->create_retry < 64)
      c->create_retry *= 2;
  }

  /* Select direction-dependent parameters */
  if (GNUNET_YES == fwd)
  {
    task_id = &c->fwd_maintenance_task;
    keepalive_task = &connection_fwd_keepalive;
  }
  else
  {
    task_id = &c->bck_maintenance_task;
    keepalive_task = &connection_bck_keepalive;
  }

  /* Check that no one scheduled it before us */
  if (NULL != *task_id)
  {
    /* No need for a _break. It can happen for instance when sending a SYNACK
     * for a duplicate SYN: the first SYNACK scheduled the task. */
    GNUNET_SCHEDULER_cancel (*task_id);
  }

  /* Schedule the task */
  *task_id = GNUNET_SCHEDULER_add_delayed (delay,
                                           keepalive_task,
                                           c);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "next keepalive in %s\n",
       GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
  GCC_check_connections ();
}


/**
 * @brief Re-initiate traffic on this connection if necessary.
 *
 * Check if there is traffic queued towards this peer
 * and the core transmit handle is NULL (traffic was stalled).
 * If so, call core tmt rdy.
 *
 * @param c Connection on which initiate traffic.
 * @param fwd Is this about fwd traffic?
 */
static void
connection_unlock_queue (struct CadetConnection *c, int fwd)
{
  struct CadetPeer *peer;

  GCC_check_connections ();
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "connection_unlock_queue %s on %s\n",
       GC_f2s (fwd), GCC_2s (c));

  if (GCC_is_terminal (c, fwd))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, " is terminal, can unlock!\n");
    return;
  }

  peer = get_hop (c, fwd);
  GCP_queue_unlock (peer, c);
  GCC_check_connections ();
}


/**
 * Cancel all transmissions that belong to a certain connection.
 *
 * If the connection is scheduled for destruction and no more messages are left,
 * the connection will be destroyed by the continuation call.
 *
 * @param c Connection which to cancel. Might be destroyed during this call.
 * @param fwd Cancel fwd traffic?
 */
static void
connection_cancel_queues (struct CadetConnection *c,
                          int fwd)
{
  struct CadetFlowControl *fc;
  struct CadetPeer *peer;

  GCC_check_connections ();
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Cancel %s queues for connection %s\n",
       GC_f2s (fwd), GCC_2s (c));
  if (NULL == c)
  {
    GNUNET_break (0);
    return;
  }

  fc = fwd ? &c->fwd_fc : &c->bck_fc;
  if (NULL != fc->poll_task)
  {
    GNUNET_SCHEDULER_cancel (fc->poll_task);
    fc->poll_task = NULL;
    LOG (GNUNET_ERROR_TYPE_DEBUG, "Cancel POLL in ccq for fc %p\n", fc);
  }
  peer = get_hop (c, fwd);
  GCP_queue_cancel (peer, c);
  GCC_check_connections ();
}


/**
 * Function called if a connection has been stalled for a while,
 * possibly due to a missed ACK. Poll the neighbor about its ACK status.
 *
 * @param cls Closure (poll ctx).
 * @param tc TaskContext.
 */
static void
connection_poll (void *cls,
                 const struct GNUNET_SCHEDULER_TaskContext *tc);


/**
 * Callback called when a queued POLL message is sent.
 *
 * @param cls Closure (FC).
 * @param c Connection this message was on.
 * @param q Queue handler this call invalidates.
 * @param type Type of message sent.
 * @param fwd Was this a FWD going message?
 * @param size Size of the message.
 */
static void
poll_sent (void *cls,
           struct CadetConnection *c,
           struct CadetConnectionQueue *q,
           uint16_t type, int fwd, size_t size)
{
  struct CadetFlowControl *fc = cls;

  if (2 == c->destroy)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "POLL canceled on shutdown\n");
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, "POLL sent for %s, scheduling new one!\n",
       GCC_2s (c));
  fc->poll_msg = NULL;
  fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
  fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
                                                &connection_poll,
                                                fc);
  LOG (GNUNET_ERROR_TYPE_DEBUG, " task %u\n", fc->poll_task);
}


/**
 * Function called if a connection has been stalled for a while,
 * possibly due to a missed ACK. Poll the neighbor about its ACK status.
 *
 * @param cls Closure (poll ctx).
 * @param tc TaskContext.
 */
static void
connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct CadetFlowControl *fc = cls;
  struct GNUNET_CADET_Poll msg;
  struct CadetConnection *c;
  int fwd;

  fc->poll_task = NULL;
  GCC_check_connections ();
  if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
  {
    return;
  }

  c = fc->c;
  fwd = fc == &c->fwd_fc;
  LOG (GNUNET_ERROR_TYPE_DEBUG, "Polling connection %s %s\n",
       GCC_2s (c),  GC_f2s (fwd));

  msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_POLL);
  msg.header.size = htons (sizeof (msg));
  msg.pid = htonl (fc->last_pid_sent);
  LOG (GNUNET_ERROR_TYPE_DEBUG, " last pid sent: %u\n", fc->last_pid_sent);
  fc->poll_msg =
      GCC_send_prebuilt_message (&msg.header, 0, fc->last_pid_sent, c,
                                 fc == &c->fwd_fc, GNUNET_YES, &poll_sent, fc);
  GNUNET_assert (NULL != fc->poll_msg);
  GCC_check_connections ();
}


/**
 * Resend all queued messages for a connection on other connections of the
 * same tunnel, if possible. The connection WILL BE DESTROYED by this function.
 *
 * @param c Connection whose messages to resend.
 * @param fwd Resend fwd messages?
 */
static void
resend_messages_and_destroy (struct CadetConnection *c, int fwd)
{
  struct GNUNET_MessageHeader *out_msg;
  struct CadetTunnel *t = c->t;
  struct CadetPeer *neighbor;
  unsigned int pending;
  int destroyed;

  GCC_check_connections ();
  c->state = CADET_CONNECTION_DESTROYED;
  c->destroy = GNUNET_YES;

  destroyed = GNUNET_NO;
  neighbor = get_hop (c, fwd);
  pending = c->pending_messages;

  while (NULL != (out_msg = GCP_connection_pop (neighbor, c, &destroyed)))
  {
    if (NULL != t)
      GCT_resend_message (out_msg, t);
    GNUNET_free (out_msg);
  }

  /* All pending messages should have been popped,
   * and the connection destroyed by the continuation.
   */
  if (GNUNET_YES != destroyed)
  {
    if (0 != pending)
    {
      GNUNET_break (0);
      GCC_debug (c, GNUNET_ERROR_TYPE_ERROR);
      if (NULL != t) GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
    }
    GCC_destroy (c);
  }
  GCC_check_connections ();
}


/**
 * Generic connection timeout implementation.
 *
 * Timeout function due to lack of keepalive/traffic from an endpoint.
 * Destroys connection if called.
 *
 * @param c Connection to destroy.
 * @param fwd Was the timeout from the origin? (FWD timeout)
 */
static void
connection_timeout (struct CadetConnection *c, int fwd)
{
  struct CadetFlowControl *reverse_fc;

  GCC_check_connections ();
  reverse_fc = fwd ? &c->bck_fc : &c->fwd_fc;

  LOG (GNUNET_ERROR_TYPE_INFO,
       "Connection %s %s timed out. Destroying.\n",
       GCC_2s (c),
       GC_f2s (fwd));
  GCC_debug (c, GNUNET_ERROR_TYPE_DEBUG);

  if (GCC_is_origin (c, fwd)) /* Loopback? Something is wrong! */
  {
    GNUNET_break (0);
    return;
  }

  /* If dest, salvage queued traffic. */
  if (GCC_is_origin (c, !fwd))
  {
    const struct GNUNET_PeerIdentity *next_hop;

    next_hop = GCP_get_id (fwd ? get_prev_hop (c) : get_next_hop (c));
    send_broken_unknown (&c->id, &my_full_id, NULL, next_hop);
    if (0 < reverse_fc->queue_n)
      resend_messages_and_destroy (c, !fwd);
    GCC_check_connections ();
    return;
  }

  GCC_destroy (c);
  GCC_check_connections ();
}


/**
 * Timeout function due to lack of keepalive/traffic from the owner.
 * Destroys connection if called.
 *
 * @param cls Closure (connection to destroy).
 * @param tc TaskContext.
 */
static void
connection_fwd_timeout (void *cls,
                        const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct CadetConnection *c = cls;

  c->fwd_maintenance_task = NULL;
  if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
    return;
  GCC_check_connections ();
  connection_timeout (c, GNUNET_YES);
  GCC_check_connections ();
}


/**
 * Timeout function due to lack of keepalive/traffic from the destination.
 * Destroys connection if called.
 *
 * @param cls Closure (connection to destroy).
 * @param tc TaskContext
 */
static void
connection_bck_timeout (void *cls,
                        const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct CadetConnection *c = cls;

  c->bck_maintenance_task = NULL;
  if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
    return;
  GCC_check_connections ();
  connection_timeout (c, GNUNET_NO);
  GCC_check_connections ();
}


/**
 * Resets the connection timeout task, some other message has done the
 * task's job.
 * - For the first peer on the direction this means to send
 *   a keepalive or a path confirmation message (either create or ACK).
 * - For all other peers, this means to destroy the connection,
 *   due to lack of activity.
 * Starts the timeout if no timeout was running (connection just created).
 *
 * @param c Connection whose timeout to reset.
 * @param fwd Is this forward?
 *
 * TODO use heap to improve efficiency of scheduler.
 */
static void
connection_reset_timeout (struct CadetConnection *c, int fwd)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s reset timeout\n", GC_f2s (fwd));
  if (GCC_is_origin (c, fwd)) /* Startpoint */
  {
    schedule_next_keepalive (c, fwd);
  }
  else /* Relay, endpoint. */
  {
    struct GNUNET_TIME_Relative delay;
    struct GNUNET_SCHEDULER_Task * *ti;
    GNUNET_SCHEDULER_TaskCallback f;

    ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;

    if (NULL != *ti)
      GNUNET_SCHEDULER_cancel (*ti);
    delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  timing out in %s\n",
         GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_NO));
    f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
    *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
  }
}


/**
 * Iterator to compare each connection's path with the path of a new connection.
 *
 * If the connection conincides, the c member of path is set to the connection
 * and the destroy flag of the connection is set.
 *
 * @param cls Closure (new path).
 * @param c Connection in the tunnel to check.
 */
static void
check_path (void *cls, struct CadetConnection *c)
{
  struct CadetConnection *new_conn = cls;
  struct CadetPeerPath *path = new_conn->path;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "  checking %s (%p), length %u\n",
       GCC_2s (c), c, c->path->length);

  if (c != new_conn
      && c->destroy == GNUNET_NO
      && c->state != CADET_CONNECTION_BROKEN
      && c->state != CADET_CONNECTION_DESTROYED
      && path_equivalent (path, c->path))
  {
    new_conn->destroy = GNUNET_YES;
    new_conn->path->c = c;
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  MATCH!\n");
  }
}


/**
 * Finds out if this path is already being used by an existing connection.
 *
 * Checks the tunnel towards the destination to see if it contains
 * any connection with the same path.
 *
 * If the existing connection is ready, it is kept.
 * Otherwise if the sender has a smaller ID that ours, we accept it (and
 * the peer will eventually reject our attempt).
 *
 * @param path Path to check.
 * @return #GNUNET_YES if the tunnel has a connection with the same path,
 *         #GNUNET_NO otherwise.
 */
static int
does_connection_exist (struct CadetConnection *conn)
{
  struct CadetPeer *p;
  struct CadetTunnel *t;
  struct CadetConnection *c;

  p = GCP_get_short (conn->path->peers[0], GNUNET_NO);
  if (NULL == p)
    return GNUNET_NO;
  t = GCP_get_tunnel (p);
  if (NULL == t)
    return GNUNET_NO;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking for duplicates\n");

  GCT_iterate_connections (t, &check_path, conn);

  if (GNUNET_YES == conn->destroy)
  {
    c = conn->path->c;
    conn->destroy = GNUNET_NO;
    conn->path->c = conn;
    LOG (GNUNET_ERROR_TYPE_DEBUG, " found duplicate of %s\n", GCC_2s (conn));
    LOG (GNUNET_ERROR_TYPE_DEBUG, " duplicate: %s\n", GCC_2s (c));
    GCC_debug (c, GNUNET_ERROR_TYPE_DEBUG);
    if (CADET_CONNECTION_READY == c->state)
    {
      /* The other peer confirmed a live connection with this path,
       * why is it trying to duplicate it. */
      GNUNET_STATISTICS_update (stats, "# duplicate connections", 1, GNUNET_NO);
      return GNUNET_YES;
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG, " duplicate not valid, connection unique\n");
    return GNUNET_NO;
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, " %s has no duplicates\n", GCC_2s (conn));
    return GNUNET_NO;
  }
}


/**
 * @brief Check if the tunnel this connection belongs to has any other
 * connection with the same path, and destroy one if so.
 *
 * @param cls Closure (connection to check).
 * @param tc Task context.
 */
static void
check_duplicates (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct CadetConnection *c = cls;

  c->check_duplicates_task = NULL;
  if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
    return;

  if (GNUNET_YES == does_connection_exist (c))
  {
    GCT_debug (c->t, GNUNET_ERROR_TYPE_DEBUG);
    send_broken (c, &my_full_id, &my_full_id, GCC_is_origin (c, GNUNET_YES));
    GCC_destroy (c);
  }
}



/**
 * Wait for enough time to let any dead connections time out and check for
 * any remaining duplicates.
 *
 * @param c Connection that is a potential duplicate.
 */
static void
schedule_check_duplicates (struct CadetConnection *c)
{
  struct GNUNET_TIME_Relative delay;

  if (NULL != c->check_duplicates_task)
    return;

  delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 5);
  c->check_duplicates_task = GNUNET_SCHEDULER_add_delayed (delay,
                                                           &check_duplicates,
                                                           c);
}



/**
 * Add the connection to the list of both neighbors.
 *
 * @param c Connection.
 *
 * @return #GNUNET_OK if everything went fine
 *         #GNUNET_SYSERR if the was an error and @c c is malformed.
 */
static int
register_neighbors (struct CadetConnection *c)
{
  c->next_peer = get_next_hop (c);
  c->prev_peer = get_prev_hop (c);
  GNUNET_assert (c->next_peer != c->prev_peer);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "register neighbors for connection %s\n",
       GCC_2s (c));
  path_debug (c->path);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "own pos %u\n", c->own_pos);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "putting connection %s to next peer %p\n",
       GCC_2s (c),
       c->next_peer);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "next peer %p %s\n",
       c->next_peer,
       GCP_2s (c->next_peer));
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "putting connection %s to prev peer %p\n",
       GCC_2s (c),
       c->prev_peer);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "prev peer %p %s\n",
       c->prev_peer,
       GCP_2s (c->prev_peer));

  if ( (GNUNET_NO == GCP_is_neighbor (c->next_peer)) ||
       (GNUNET_NO == GCP_is_neighbor (c->prev_peer)) )
  {
    if (GCC_is_origin (c, GNUNET_YES))
      GNUNET_STATISTICS_update (stats, "# local bad paths", 1, GNUNET_NO);
    GNUNET_STATISTICS_update (stats, "# bad paths", 1, GNUNET_NO);

    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "  register neighbors failed\n");
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "  prev: %s, neighbor?: %d\n",
         GCP_2s (c->prev_peer),
         GCP_is_neighbor (c->prev_peer));
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "  next: %s, neighbor?: %d\n",
         GCP_2s (c->next_peer),
         GCP_is_neighbor (c->next_peer));
    return GNUNET_SYSERR;
  }
  GCP_add_connection (c->next_peer, c, GNUNET_NO);
  GCP_add_connection (c->prev_peer, c, GNUNET_YES);

  return GNUNET_OK;
}


/**
 * Remove the connection from the list of both neighbors.
 *
 * @param c Connection.
 */
static void
unregister_neighbors (struct CadetConnection *c)
{
//  struct CadetPeer *peer; FIXME dont use next_peer, prev_peer
  /* Either already unregistered or never got registered, it's ok either way. */
  if (NULL == c->path)
    return;
  if (NULL != c->next_peer)
  {
    GCP_remove_connection (c->next_peer, c);
    c->next_peer = NULL;
  }
  if (NULL != c->prev_peer)
  {
    GCP_remove_connection (c->prev_peer, c);
    c->prev_peer = NULL;
  }
}


/**
 * Bind the connection to the peer and the tunnel to that peer.
 *
 * If the peer has no tunnel, create one. Update tunnel and connection
 * data structres to reflect new status.
 *
 * @param c Connection.
 * @param peer Peer.
 */
static void
add_to_peer (struct CadetConnection *c,
             struct CadetPeer *peer)
{
  GCP_add_tunnel (peer);
  c->t = GCP_get_tunnel (peer);
  GCT_add_connection (c->t, c);
}


/**
 * Log receipt of message on stderr (INFO level).
 *
 * @param message Message received.
 * @param peer Peer who sent the message.
 * @param hash Connection ID.
 */
static void
log_message (const struct GNUNET_MessageHeader *message,
             const struct GNUNET_PeerIdentity *peer,
             const struct GNUNET_CADET_Hash *hash)
{
  uint16_t size;

  size = ntohs (message->size);
  LOG (GNUNET_ERROR_TYPE_INFO, "\n");
  LOG (GNUNET_ERROR_TYPE_INFO, "\n");
  LOG (GNUNET_ERROR_TYPE_INFO, "<-- %s on conn %s from %s, %6u bytes\n",
       GC_m2s (ntohs (message->type)), GNUNET_h2s (GC_h2hc (hash)),
       GNUNET_i2s (peer), (unsigned int) size);
}

/******************************************************************************/
/********************************    API    ***********************************/
/******************************************************************************/

/**
 * Core handler for connection creation.
 *
 * @param cls Closure (unused).
 * @param peer Sender (neighbor).
 * @param message Message.
 * @return #GNUNET_OK to keep the connection open,
 *         #GNUNET_SYSERR to close it (signal serious error)
 */
int
GCC_handle_create (void *cls,
                   const struct GNUNET_PeerIdentity *peer,
                   const struct GNUNET_MessageHeader *message)
{
  struct GNUNET_CADET_ConnectionCreate *msg;
  struct GNUNET_PeerIdentity *id;
  struct GNUNET_CADET_Hash *cid;
  struct CadetPeerPath *path;
  struct CadetPeer *dest_peer;
  struct CadetPeer *orig_peer;
  struct CadetConnection *c;
  unsigned int own_pos;
  uint16_t size;

  GCC_check_connections ();
  /* Check size */
  size = ntohs (message->size);
  if (size < sizeof (struct GNUNET_CADET_ConnectionCreate))
  {
    GNUNET_break_op (0);
    return GNUNET_OK;
  }

  /* Calculate hops */
  size -= sizeof (struct GNUNET_CADET_ConnectionCreate);
  if (size % sizeof (struct GNUNET_PeerIdentity))
  {
    GNUNET_break_op (0);
    return GNUNET_OK;
  }
  if (0 != size % sizeof (struct GNUNET_PeerIdentity))
  {
    GNUNET_break_op (0);
    return GNUNET_OK;
  }
  size /= sizeof (struct GNUNET_PeerIdentity);
  if (1 > size)
  {
    GNUNET_break_op (0);
    return GNUNET_OK;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);

  /* Get parameters */
  msg = (struct GNUNET_CADET_ConnectionCreate *) message;
  cid = &msg->cid;
  log_message (message, peer, cid);
  id = (struct GNUNET_PeerIdentity *) &msg[1];
  LOG (GNUNET_ERROR_TYPE_DEBUG, "    origin: %s\n", GNUNET_i2s (id));

  /* Create connection */
  c = connection_get (cid);
  if (NULL == c)
  {
    path = path_build_from_peer_ids ((struct GNUNET_PeerIdentity *) &msg[1],
                                     size, myid, &own_pos);
    if (NULL == path)
    {
      /* Path was malformed, probably our own ID was not in it. */
      GNUNET_STATISTICS_update (stats, "# malformed paths", 1, GNUNET_NO);
      GNUNET_break_op (0);
      return GNUNET_OK;
    }

    if (0 == own_pos)
    {
      /* We received this request from a neighbor, we cannot be origin */
      GNUNET_STATISTICS_update (stats, "# fake paths", 1, GNUNET_NO);
      GNUNET_break_op (0);
      path_destroy (path);
      return GNUNET_OK;
    }

    LOG (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
    c = GCC_new (cid, NULL, path, own_pos);
    if (NULL == c)
    {
      if (path->length - 1 == own_pos)
      {
        /* If we are destination, why did the creation fail? */
        GNUNET_break (0);
        path_destroy (path);
        GCC_check_connections ();
        return GNUNET_OK;
      }
      send_broken_unknown (cid, &my_full_id,
                           GNUNET_PEER_resolve2 (path->peers[own_pos + 1]),
                           peer);
      path_destroy (path);
      GCC_check_connections ();
      return GNUNET_OK;
    }
    GCP_add_path_to_all (path, GNUNET_NO);
    connection_reset_timeout (c, GNUNET_YES);
  }
  else
  {
    path = path_duplicate (c->path);
  }
  if (CADET_CONNECTION_NEW == c->state)
    connection_change_state (c, CADET_CONNECTION_SENT);

  /* Remember peers */
  dest_peer = GCP_get (&id[size - 1], GNUNET_YES);
  orig_peer = GCP_get (&id[0], GNUNET_YES);

  /* Is it a connection to us? */
  if (c->own_pos == path->length - 1)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
    GCP_add_path_to_origin (orig_peer, path_duplicate (path), GNUNET_YES);

    add_to_peer (c, orig_peer);
    if (GNUNET_YES == does_connection_exist (c))
    {
      /* Peer created a connection equal to one we think exists
       * and is fine.
       * Solution: Keep both and postpone disambiguation. In the meantime
       * the connection will time out or peer will inform us it is broken.
       *
       * Other options:
       * - Use explicit duplicate.
       * - Accept new conn and destroy the old. (interruption in higher level)
       * - Keep the one with higher ID / created by peer with higher ID. */
       schedule_check_duplicates (c);
    }

    if (CADET_TUNNEL_NEW == GCT_get_cstate (c->t))
      GCT_change_cstate (c->t,  CADET_TUNNEL_WAITING);

    send_connection_ack (c, GNUNET_NO);
    if (CADET_CONNECTION_SENT == c->state)
      connection_change_state (c, CADET_CONNECTION_ACK);
  }
  else
  {
    /* It's for somebody else! Retransmit. */
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
    GCP_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
    GCP_add_path_to_origin (orig_peer, path_duplicate (path), GNUNET_NO);
    GNUNET_assert (NULL == GCC_send_prebuilt_message (message, 0, 0, c,
                                                      GNUNET_YES, GNUNET_YES,
                                                      NULL, NULL));
  }
  path_destroy (path);
  GCC_check_connections ();
  return GNUNET_OK;
}


/**
 * Core handler for path confirmations.
 *
 * @param cls closure
 * @param message message
 * @param peer peer identity this notification is about
 * @return #GNUNET_OK to keep the connection open,
 *         #GNUNET_SYSERR to close it (signal serious error)
 */
int
GCC_handle_confirm (void *cls,
                    const struct GNUNET_PeerIdentity *peer,
                    const struct GNUNET_MessageHeader *message)
{
  struct GNUNET_CADET_ConnectionACK *msg;
  struct CadetConnection *c;
  struct CadetPeerPath *p;
  struct CadetPeer *pi;
  enum CadetConnectionState oldstate;
  int fwd;

  GCC_check_connections ();
  msg = (struct GNUNET_CADET_ConnectionACK *) message;
  log_message (message, peer, &msg->cid);
  c = connection_get (&msg->cid);
  if (NULL == c)
  {
    GNUNET_STATISTICS_update (stats, "# control on unknown connection",
                              1, GNUNET_NO);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "  don't know the connection!\n");
    send_broken_unknown (&msg->cid, &my_full_id, NULL, peer);
    GCC_check_connections ();
    return GNUNET_OK;
  }

  oldstate = c->state;
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n", GNUNET_i2s (peer));
  pi = GCP_get (peer, GNUNET_YES);
  if (get_next_hop (c) == pi)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
    fwd = GNUNET_NO;
    if (CADET_CONNECTION_SENT == oldstate)
      connection_change_state (c, CADET_CONNECTION_ACK);
  }
  else if (get_prev_hop (c) == pi)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  FINAL ACK\n");
    fwd = GNUNET_YES;
    connection_change_state (c, CADET_CONNECTION_READY);
  }
  else
  {
    GNUNET_break_op (0);
    return GNUNET_OK;
  }

  connection_reset_timeout (c, fwd);

  /* Add path to peers? */
  p = c->path;
  if (NULL != p)
  {
    GCP_add_path_to_all (p, GNUNET_YES);
  }
  else
  {
    GNUNET_break (0);
  }

  /* Message for us as creator? */
  if (GCC_is_origin (c, GNUNET_YES))
  {
    if (GNUNET_NO != fwd)
    {
      GNUNET_break_op (0);
      return GNUNET_OK;
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");

    /* If just created, cancel the short timeout and start a long one */
    if (CADET_CONNECTION_SENT == oldstate)
      connection_reset_timeout (c, GNUNET_YES);

    /* Change connection state */
    connection_change_state (c, CADET_CONNECTION_READY);
    send_connection_ack (c, GNUNET_YES);

    /* Change tunnel state, trigger KX */
    if (CADET_TUNNEL_WAITING == GCT_get_cstate (c->t))
      GCT_change_cstate (c->t, CADET_TUNNEL_READY);
    GCC_check_connections ();
    return GNUNET_OK;
  }

  /* Message for us as destination? */
  if (GCC_is_terminal (c, GNUNET_YES))
  {
    if (GNUNET_YES != fwd)
    {
      GNUNET_break_op (0);
      return GNUNET_OK;
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");

    /* If just created, cancel the short timeout and start a long one */
    if (CADET_CONNECTION_ACK == oldstate)
      connection_reset_timeout (c, GNUNET_NO);

    /* Change tunnel state */
    if (CADET_TUNNEL_WAITING == GCT_get_cstate (c->t))
      GCT_change_cstate (c->t, CADET_TUNNEL_READY);
    GCC_check_connections ();
    return GNUNET_OK;
  }

  LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
  GNUNET_assert (NULL ==
                 GCC_send_prebuilt_message (message, 0, 0, c, fwd,
                                            GNUNET_YES, NULL, NULL));
  GCC_check_connections ();
  return GNUNET_OK;
}


/**
 * Core handler for notifications of broken connections.
 *
 * @param cls Closure (unused).
 * @param id Peer identity of sending neighbor.
 * @param message Message.
 * @return #GNUNET_OK to keep the connection open,
 *         #GNUNET_SYSERR to close it (signal serious error)
 */
int
GCC_handle_broken (void* cls,
                   const struct GNUNET_PeerIdentity* id,
                   const struct GNUNET_MessageHeader* message)
{
  struct GNUNET_CADET_ConnectionBroken *msg;
  struct CadetConnection *c;
  struct CadetTunnel *t;
  int pending;
  int fwd;

  GCC_check_connections ();
  msg = (struct GNUNET_CADET_ConnectionBroken *) message;
  log_message (message, id, &msg->cid);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
              GNUNET_i2s (&msg->peer1));
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
              GNUNET_i2s (&msg->peer2));
  c = connection_get (&msg->cid);
  if (NULL == c)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  duplicate CONNECTION_BROKEN\n");
    GCC_check_connections ();
    return GNUNET_OK;
  }

  t = c->t;

  fwd = is_fwd (c, id);
  c->destroy = GNUNET_YES;
  if (GCC_is_terminal (c, fwd))
  {
    struct CadetPeer *endpoint;

    if (NULL == t)
    {
      /* A terminal connection should not have 't' set to NULL. */
      GNUNET_break (0);
      GCC_debug (c, GNUNET_ERROR_TYPE_ERROR);
      return GNUNET_OK;
    }
    endpoint = GCP_get_short (c->path->peers[c->path->length - 1], GNUNET_YES);
    if (2 < c->path->length)
      path_invalidate (c->path);
    GCP_notify_broken_link (endpoint, &msg->peer1, &msg->peer2);

    c->state = CADET_CONNECTION_BROKEN;
    GCT_remove_connection (t, c);
    c->t = NULL;

    pending = c->pending_messages;
    if (0 < pending)
      resend_messages_and_destroy (c, !fwd);
    else
      GCC_destroy (c);
  }
  else
  {
    GNUNET_assert (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
                                                      GNUNET_YES, NULL, NULL));
    connection_cancel_queues (c, !fwd);
  }
  GCC_check_connections ();
  return GNUNET_OK;
}


/**
 * Core handler for tunnel destruction
 *
 * @param cls Closure (unused).
 * @param peer Peer identity of sending neighbor.
 * @param message Message.
 * @return #GNUNET_OK to keep the connection open,
 *         #GNUNET_SYSERR to close it (signal serious error)
 */
int
GCC_handle_destroy (void *cls,
                    const struct GNUNET_PeerIdentity *peer,
                    const struct GNUNET_MessageHeader *message)
{
  const struct GNUNET_CADET_ConnectionDestroy *msg;
  struct CadetConnection *c;
  int fwd;

  GCC_check_connections ();
  msg = (const struct GNUNET_CADET_ConnectionDestroy *) message;
  log_message (message, peer, &msg->cid);
  c = connection_get (&msg->cid);
  if (NULL == c)
  {
    /* Probably already got the message from another path,
     * destroyed the tunnel and retransmitted to children.
     * Safe to ignore.
     */
    GNUNET_STATISTICS_update (stats,
                              "# control on unknown connection",
                              1, GNUNET_NO);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "  connection unknown: already destroyed?\n");
    GCC_check_connections ();
    return GNUNET_OK;
  }
  fwd = is_fwd (c, peer);
  if (GNUNET_SYSERR == fwd)
  {
    GNUNET_break_op (0); /* FIXME */
    return GNUNET_OK;
  }
  if (GNUNET_NO == GCC_is_terminal (c, fwd))
  {
    GNUNET_assert (NULL ==
                   GCC_send_prebuilt_message (message, 0, 0, c, fwd,
                                              GNUNET_YES, NULL, NULL));
  }
  else if (0 == c->pending_messages)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "  directly destroying connection!\n");
    GCC_destroy (c);
    GCC_check_connections ();
    return GNUNET_OK;
  }
  c->destroy = GNUNET_YES;
  c->state = CADET_CONNECTION_DESTROYED;
  if (NULL != c->t)
  {
    GCT_remove_connection (c->t, c);
    c->t = NULL;
  }
  GCC_check_connections ();
  return GNUNET_OK;
}


/**
 * Check the message against internal state and test if it goes FWD or BCK.
 *
 * Updates the PID, state and timeout values for the connection.
 *
 * @param message Message to check. It must belong to an existing connection.
 * @param minimum_size The message cannot be smaller than this value.
 * @param cid Connection ID (even if @a c is NULL, the ID is still needed).
 * @param c Connection this message should belong. If NULL, check fails.
 * @param neighbor Neighbor that sent the message.
 */
static int
check_message (const struct GNUNET_MessageHeader *message,
               size_t minimum_size,
               const struct GNUNET_CADET_Hash* cid,
               struct CadetConnection *c,
               const struct GNUNET_PeerIdentity *neighbor,
               uint32_t pid)
{
  GNUNET_PEER_Id neighbor_id;
  struct CadetFlowControl *fc;
  struct CadetPeer *hop;
  int fwd;
  uint16_t type;

  /* Check size */
  if (ntohs (message->size) < minimum_size)
  {
    GNUNET_break_op (0);
    LOG (GNUNET_ERROR_TYPE_WARNING, "Size %u < %u\n",
         ntohs (message->size), minimum_size);
    return GNUNET_SYSERR;
  }

  /* Check connection */
  if (NULL == c)
  {
    GNUNET_STATISTICS_update (stats,
                              "# unknown connection",
                              1, GNUNET_NO);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s on unknown connection %s\n",
         GC_m2s (ntohs (message->type)),
         GNUNET_h2s (GC_h2hc (cid)));
    send_broken_unknown (cid,
                         &my_full_id,
                         NULL,
                         neighbor);
    return GNUNET_SYSERR;
  }

  /* Check if origin is as expected */
  neighbor_id = GNUNET_PEER_search (neighbor);
  hop = get_prev_hop (c);
  if (neighbor_id == GCP_get_short_id (hop))
  {
    fwd = GNUNET_YES;
  }
  else
  {
    hop = get_next_hop (c);
    GNUNET_break (hop == c->next_peer);
    if (neighbor_id == GCP_get_short_id (hop))
    {
      fwd = GNUNET_NO;
    }
    else
    {
      /* Unexpected peer sending traffic on a connection. */
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
  }

  /* Check PID for payload messages */
  type = ntohs (message->type);
  if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type
      || GNUNET_MESSAGE_TYPE_CADET_AX == type)
  {
    fc = fwd ? &c->bck_fc : &c->fwd_fc;
    LOG (GNUNET_ERROR_TYPE_DEBUG, " PID %u (expected %u - %u)\n",
         pid, fc->last_pid_recv + 1, fc->last_ack_sent);
    if (GC_is_pid_bigger (pid, fc->last_ack_sent))
    {
      GNUNET_break_op (0);
      GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
      LOG (GNUNET_ERROR_TYPE_WARNING, "Received PID %u, (prev %u), ACK %u\n",
          pid, fc->last_pid_recv, fc->last_ack_sent);
      return GNUNET_SYSERR;
    }
    if (GC_is_pid_bigger (pid, fc->last_pid_recv))
    {
      unsigned int delta;

      delta = pid - fc->last_pid_recv;
      fc->last_pid_recv = pid;
      fc->recv_bitmap <<= delta;
      fc->recv_bitmap |= 1;
    }
    else
    {
      GNUNET_STATISTICS_update (stats, "# out of order PID", 1, GNUNET_NO);
      if (GNUNET_NO == is_ooo_ok (fc->last_pid_recv, pid, fc->recv_bitmap))
      {
        LOG (GNUNET_ERROR_TYPE_WARNING, "PID %u unexpected (%u+), dropping!\n",
             pid, fc->last_pid_recv - 31);
        return GNUNET_SYSERR;
      }
      fc->recv_bitmap |= get_recv_bitmask (fc->last_pid_recv, pid);
    }
  }

  /* Count as connection confirmation. */
  if (CADET_CONNECTION_SENT == c->state || CADET_CONNECTION_ACK == c->state)
  {
    connection_change_state (c, CADET_CONNECTION_READY);
    if (NULL != c->t)
    {
      if (CADET_TUNNEL_WAITING == GCT_get_cstate (c->t))
        GCT_change_cstate (c->t, CADET_TUNNEL_READY);
    }
  }
  connection_reset_timeout (c, fwd);

  return fwd;
}


/**
 * Generic handler for cadet network encrypted traffic.
 *
 * @param peer Peer identity this notification is about.
 * @param msg Encrypted message.
 * @return #GNUNET_OK to keep the connection open,
 *         #GNUNET_SYSERR to close it (signal serious error)
 */
static int
handle_cadet_encrypted (const struct GNUNET_PeerIdentity *peer,
                        const struct GNUNET_MessageHeader *message)
{
  const struct GNUNET_CADET_Encrypted *otr_msg;
  const struct GNUNET_CADET_AX *ax_msg;
  const struct GNUNET_CADET_Hash* cid;
  struct CadetConnection *c;
  size_t minumum_size;
  size_t overhead;
  uint32_t pid;
  uint32_t ttl;
  int fwd;

  GCC_check_connections ();
  if (GNUNET_MESSAGE_TYPE_CADET_AX == ntohs (message->type))
  {
    overhead = sizeof (struct GNUNET_CADET_AX);
    ax_msg = (const struct GNUNET_CADET_AX *) message;
    cid = &ax_msg->cid;
    pid = ntohl (ax_msg->pid);
    otr_msg = NULL;
  }
  else
  {
    overhead = sizeof (struct GNUNET_CADET_Encrypted);
    otr_msg = (const struct GNUNET_CADET_Encrypted *) message;
    cid = &otr_msg->cid;
    pid = ntohl (otr_msg->pid);
  }

  log_message (message, peer, cid);

  minumum_size = sizeof (struct GNUNET_MessageHeader) + overhead;
  c = connection_get (cid);
  fwd = check_message (message,
                       minumum_size,
                       cid,
                       c,
                       peer,
                       pid);

  /* If something went wrong, discard message. */
  if (GNUNET_SYSERR == fwd)
  {
    GCC_check_connections ();
    return GNUNET_OK;
  }

  /* Is this message for us? */
  if (GCC_is_terminal (c, fwd))
  {
    GNUNET_STATISTICS_update (stats, "# received encrypted", 1, GNUNET_NO);

    if (NULL == c->t)
    {
      GNUNET_break (GNUNET_NO != c->destroy);
      return GNUNET_OK;
    }
    GCT_handle_encrypted (c->t, message);
    GCC_send_ack (c, fwd, GNUNET_NO);
    GCC_check_connections ();
    return GNUNET_OK;
  }

  /* Message not for us: forward to next hop */
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
  if (NULL != otr_msg) /* only otr has ttl */
  {
    ttl = ntohl (otr_msg->ttl);
    LOG (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
    if (ttl == 0)
    {
      GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
      LOG (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
      GCC_send_ack (c, fwd, GNUNET_NO);
      GCC_check_connections ();
      return GNUNET_OK;
    }
  }

  GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
  GNUNET_assert (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
                                                    GNUNET_NO, NULL, NULL));
  GCC_check_connections ();
  return GNUNET_OK;
}


/**
 * Generic handler for cadet network encrypted traffic.
 *
 * @param peer Peer identity this notification is about.
 * @param msg Encrypted message.
 * @return #GNUNET_OK to keep the connection open,
 *         #GNUNET_SYSERR to close it (signal serious error)
 */
static int
handle_cadet_kx (const struct GNUNET_PeerIdentity *peer,
                 const struct GNUNET_CADET_KX *msg)
{
  const struct GNUNET_CADET_Hash* cid;
  struct CadetConnection *c;
  size_t expected_size;
  int fwd;

  GCC_check_connections ();
  cid = &msg->cid;
  log_message (&msg->header, peer, cid);

  expected_size = sizeof (struct GNUNET_CADET_KX)
                  + sizeof (struct GNUNET_MessageHeader);
  c = connection_get (cid);
  fwd = check_message (&msg->header,
                       expected_size,
                       cid,
                       c,
                       peer,
                       0);

  /* If something went wrong, discard message. */
  if (GNUNET_SYSERR == fwd)
    return GNUNET_OK;

  /* Is this message for us? */
  if (GCC_is_terminal (c, fwd))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
    GNUNET_STATISTICS_update (stats, "# received KX", 1, GNUNET_NO);
    if (NULL == c->t)
    {
      GNUNET_break (0);
      return GNUNET_OK;
    }
    GCT_handle_kx (c->t, &msg[1].header);
    GCC_check_connections ();
    return GNUNET_OK;
  }

  /* Message not for us: forward to next hop */
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
  GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
  GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg->header, 0, 0, c, fwd,
                                                    GNUNET_NO, NULL, NULL));
  GCC_check_connections ();
  return GNUNET_OK;
}


/**
 * Core handler for key exchange traffic (ephemeral key, ping, pong).
 *
 * @param cls Closure (unused).
 * @param message Message received.
 * @param peer Peer who sent the message.
 * @return #GNUNET_OK to keep the connection open,
 *         #GNUNET_SYSERR to close it (signal serious error)
 */
int
GCC_handle_kx (void *cls,
               const struct GNUNET_PeerIdentity *peer,
               const struct GNUNET_MessageHeader *message)
{
  GCC_check_connections ();
  return handle_cadet_kx (peer, (struct GNUNET_CADET_KX *) message);
}


/**
 * Core handler for encrypted cadet network traffic (channel mgmt, data).
 *
 * @param cls Closure (unused).
 * @param message Message received.
 * @param peer Peer who sent the message.
 * @return #GNUNET_OK to keep the connection open,
 *         #GNUNET_SYSERR to close it (signal serious error)
 */
int
GCC_handle_encrypted (void *cls, const struct GNUNET_PeerIdentity *peer,
                      const struct GNUNET_MessageHeader *message)
{
  GCC_check_connections ();
  return handle_cadet_encrypted (peer, message);
}


/**
 * Core handler for cadet network traffic point-to-point acks.
 *
 * @param cls closure
 * @param message message
 * @param peer peer identity this notification is about
 * @return #GNUNET_OK to keep the connection open,
 *         #GNUNET_SYSERR to close it (signal serious error)
 */
int
GCC_handle_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
                const struct GNUNET_MessageHeader *message)
{
  struct GNUNET_CADET_ACK *msg;
  struct CadetConnection *c;
  struct CadetFlowControl *fc;
  GNUNET_PEER_Id id;
  uint32_t ack;
  int fwd;

  GCC_check_connections ();
  msg = (struct GNUNET_CADET_ACK *) message;
  log_message (message, peer, &msg->cid);
  c = connection_get (&msg->cid);
  if (NULL == c)
  {
    GNUNET_STATISTICS_update (stats,
                              "# ack on unknown connection",
                              1,
                              GNUNET_NO);
    send_broken_unknown (&msg->cid,
                         &my_full_id,
                         NULL,
                         peer);
    GCC_check_connections ();
    return GNUNET_OK;
  }

  /* Is this a forward or backward ACK? */
  id = GNUNET_PEER_search (peer);
  if (GCP_get_short_id (get_next_hop (c)) == id)
  {
    fc = &c->fwd_fc;
    fwd = GNUNET_YES;
  }
  else if (GCP_get_short_id (get_prev_hop (c)) == id)
  {
    fc = &c->bck_fc;
    fwd = GNUNET_NO;
  }
  else
  {
    GNUNET_break_op (0);
    return GNUNET_OK;
  }

  ack = ntohl (msg->ack);
  LOG (GNUNET_ERROR_TYPE_DEBUG, " %s ACK %u (was %u)\n",
       GC_f2s (fwd), ack, fc->last_ack_recv);
  if (GC_is_pid_bigger (ack, fc->last_ack_recv))
    fc->last_ack_recv = ack;

  /* Cancel polling if the ACK is big enough. */
  if (NULL != fc->poll_task &&
      GC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
    GNUNET_SCHEDULER_cancel (fc->poll_task);
    fc->poll_task = NULL;
    fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
  }

  connection_unlock_queue (c, fwd);
  GCC_check_connections ();
  return GNUNET_OK;
}


/**
 * Core handler for cadet network traffic point-to-point ack polls.
 *
 * @param cls closure
 * @param message message
 * @param peer peer identity this notification is about
 * @return #GNUNET_OK to keep the connection open,
 *         #GNUNET_SYSERR to close it (signal serious error)
 */
int
GCC_handle_poll (void *cls,
                 const struct GNUNET_PeerIdentity *peer,
                 const struct GNUNET_MessageHeader *message)
{
  struct GNUNET_CADET_Poll *msg;
  struct CadetConnection *c;
  struct CadetFlowControl *fc;
  GNUNET_PEER_Id id;
  uint32_t pid;
  int fwd;

  GCC_check_connections ();
  msg = (struct GNUNET_CADET_Poll *) message;
  log_message (message, peer, &msg->cid);
  c = connection_get (&msg->cid);
  if (NULL == c)
  {
    GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
                              GNUNET_NO);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "POLL message on unknown connection %s!\n",
         GNUNET_h2s (GC_h2hc (&msg->cid)));
    send_broken_unknown (&msg->cid,
                         &my_full_id,
                         NULL,
                         peer);
    GCC_check_connections ();
    return GNUNET_OK;
  }

  /* Is this a forward or backward ACK?
   * Note: a poll should never be needed in a loopback case,
   * since there is no possiblility of packet loss there, so
   * this way of discerining FWD/BCK should not be a problem.
   */
  id = GNUNET_PEER_search (peer);
  if (GCP_get_short_id (get_next_hop (c)) == id)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
    fc = &c->fwd_fc;
  }
  else if (GCP_get_short_id (get_prev_hop (c)) == id)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
    fc = &c->bck_fc;
  }
  else
  {
    GNUNET_break_op (0);
    return GNUNET_OK;
  }

  pid = ntohl (msg->pid);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n", pid, fc->last_pid_recv);
  fc->last_pid_recv = pid;
  fwd = fc == &c->bck_fc;
  GCC_send_ack (c, fwd, GNUNET_YES);
  GCC_check_connections ();

  return GNUNET_OK;
}


/**
 * Send an ACK on the appropriate connection/channel, depending on
 * the direction and the position of the peer.
 *
 * @param c Which connection to send the hop-by-hop ACK.
 * @param fwd Is this a fwd ACK? (will go dest->root).
 * @param force Send the ACK even if suboptimal (e.g. requested by POLL).
 */
void
GCC_send_ack (struct CadetConnection *c, int fwd, int force)
{
  unsigned int buffer;

  GCC_check_connections ();
  LOG (GNUNET_ERROR_TYPE_DEBUG, "GCC send %s ACK on %s\n",
       GC_f2s (fwd), GCC_2s (c));

  if (NULL == c)
  {
    GNUNET_break (0);
    return;
  }

  if (GNUNET_NO != c->destroy)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  being destroyed, why bother...\n");
    GCC_check_connections ();
    return;
  }

  /* Get available buffer space */
  if (GCC_is_terminal (c, fwd))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from all channels\n");
    buffer = GCT_get_channels_buffer (c->t);
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from one connection\n");
    buffer = GCC_get_buffer (c, fwd);
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer available: %u\n", buffer);
  if (0 == buffer && GNUNET_NO == force)
  {
    GCC_check_connections ();
    return;
  }

  /* Send available buffer space */
  if (GCC_is_origin (c, fwd))
  {
    GNUNET_assert (NULL != c->t);
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channels...\n");
    GCT_unchoke_channels (c->t);
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on connection\n");
    send_ack (c, buffer, fwd, force);
  }
  GCC_check_connections ();
}


/**
 * Initialize the connections subsystem
 *
 * @param c Configuration handle.
 */
void
GCC_init (const struct GNUNET_CONFIGURATION_Handle *c)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_MSGS_QUEUE",
                                             &max_msgs_queue))
  {
    GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
                               "CADET", "MAX_MSGS_QUEUE", "MISSING");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }

  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_CONNECTIONS",
                                             &max_connections))
  {
    GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
                               "CADET", "MAX_CONNECTIONS", "MISSING");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }

  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REFRESH_CONNECTION_TIME",
                                           &refresh_connection_time))
  {
    GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
                               "CADET", "REFRESH_CONNECTION_TIME", "MISSING");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  create_connection_time = GNUNET_TIME_UNIT_SECONDS;
  connections = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_NO);
}


/**
 * Destroy each connection on shutdown.
 *
 * @param cls Closure (unused).
 * @param key Current key code (CID, unused).
 * @param value Value in the hash map (`struct CadetConnection`)
 *
 * @return #GNUNET_YES, because we should continue to iterate
 */
static int
shutdown_iterator (void *cls,
                   const struct GNUNET_HashCode *key,
                   void *value)
{
  struct CadetConnection *c = value;

  c->state = CADET_CONNECTION_DESTROYED;
  GCC_destroy (c);
  return GNUNET_YES;
}


/**
 * Shut down the connections subsystem.
 */
void
GCC_shutdown (void)
{
  GCC_check_connections ();
  GNUNET_CONTAINER_multihashmap_iterate (connections,
                                         &shutdown_iterator,
                                         NULL);
  GNUNET_CONTAINER_multihashmap_destroy (connections);
  connections = NULL;
}


/**
 * Create a connection.
 *
 * @param cid Connection ID (either created locally or imposed remotely).
 * @param t Tunnel this connection belongs to (or NULL);
 * @param path Path this connection has to use (copy is made).
 * @param own_pos Own position in the @c path path.
 *
 * @return Newly created connection, NULL in case of error (own id not in path).
 */
struct CadetConnection *
GCC_new (const struct GNUNET_CADET_Hash *cid,
         struct CadetTunnel *t,
         struct CadetPeerPath *path,
         unsigned int own_pos)
{
  struct CadetConnection *c;
  struct CadetPeerPath *cpath;

  GCC_check_connections ();
  cpath = path_duplicate (path);
  GNUNET_assert (NULL != cpath);
  c = GNUNET_new (struct CadetConnection);
  c->id = *cid;
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multihashmap_put (connections,
                                                    GCC_get_h (c), c,
                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  fc_init (&c->fwd_fc);
  fc_init (&c->bck_fc);
  c->fwd_fc.c = c;
  c->bck_fc.c = c;

  c->t = t;
  GNUNET_assert (own_pos <= cpath->length - 1);
  c->own_pos = own_pos;
  c->path = cpath;
  cpath->c = c;
  if (GNUNET_OK != register_neighbors (c))
  {
    if (0 == own_pos)
    {
      /* We were the origin of this request, this means we have invalid
       * info about the paths to reach the destination. We must invalidate
       * the *original* path to avoid trying it again in the next minute.
       */
      if (2 < path->length)
        path_invalidate (path);
      else
      {
        GNUNET_break (0);
        GCT_debug(t, GNUNET_ERROR_TYPE_WARNING);
      }
      c->t = NULL;
    }
    path_destroy (c->path);
    c->path = NULL;
    GCC_destroy (c);
    return NULL;
  }
  LOG (GNUNET_ERROR_TYPE_INFO, "New connection %s\n", GCC_2s (c));
  GCC_check_connections ();
  return c;
}


void
GCC_destroy (struct CadetConnection *c)
{
  GCC_check_connections ();
  if (NULL == c)
  {
    GNUNET_break (0);
    return;
  }

  if (2 == c->destroy) /* cancel queues -> GCP_queue_cancel -> q_destroy -> */
    return;            /* -> message_sent -> GCC_destroy. Don't loop. */
  c->destroy = 2;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "destroying connection %s\n",
       GCC_2s (c));
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       " fc's f: %p, b: %p\n",
       &c->fwd_fc, &c->bck_fc);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       " fc tasks f: %u, b: %u\n",
       c->fwd_fc.poll_task,
       c->bck_fc.poll_task);

  /* Cancel all traffic */
  if (NULL != c->path)
  {
    connection_cancel_queues (c, GNUNET_YES);
    connection_cancel_queues (c, GNUNET_NO);
  }
  unregister_neighbors (c);
  path_destroy (c->path);
  c->path = NULL;

  /* Cancel maintainance task (keepalive/timeout) */
  if (NULL != c->fwd_fc.poll_msg)
  {
    GCC_cancel (c->fwd_fc.poll_msg);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 " POLL msg FWD canceled\n");
  }
  if (NULL != c->bck_fc.poll_msg)
  {
    GCC_cancel (c->bck_fc.poll_msg);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 " POLL msg BCK canceled\n");
  }

  /* Delete from tunnel */
  if (NULL != c->t)
    GCT_remove_connection (c->t, c);

  if (NULL != c->check_duplicates_task)
    GNUNET_SCHEDULER_cancel (c->check_duplicates_task);
  if (NULL != c->fwd_maintenance_task)
    GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
  if (NULL != c->bck_maintenance_task)
    GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
  if (NULL != c->fwd_fc.poll_task)
  {
    GNUNET_SCHEDULER_cancel (c->fwd_fc.poll_task);
    LOG (GNUNET_ERROR_TYPE_DEBUG, " POLL task FWD canceled\n");
  }
  if (NULL != c->bck_fc.poll_task)
  {
    GNUNET_SCHEDULER_cancel (c->bck_fc.poll_task);
    LOG (GNUNET_ERROR_TYPE_DEBUG, " POLL task BCK canceled\n");
  }
  if (GNUNET_NO == c->was_removed)
  {
    GNUNET_break (GNUNET_YES ==
                  GNUNET_CONTAINER_multihashmap_remove (connections,
                                                        GCC_get_h (c),
                                                        c));
  }
  GNUNET_STATISTICS_update (stats,
                            "# connections",
                            -1,
                            GNUNET_NO);
  GNUNET_free (c);
  GCC_check_connections ();
}


/**
 * Get the connection ID.
 *
 * @param c Connection to get the ID from.
 *
 * @return ID of the connection.
 */
const struct GNUNET_CADET_Hash *
GCC_get_id (const struct CadetConnection *c)
{
  return &c->id;
}


/**
 * Get the connection ID.
 *
 * @param c Connection to get the ID from.
 *
 * @return ID of the connection.
 */
const struct GNUNET_HashCode *
GCC_get_h (const struct CadetConnection *c)
{
  return GC_h2hc (&c->id);
}


/**
 * Get the connection path.
 *
 * @param c Connection to get the path from.
 *
 * @return path used by the connection.
 */
const struct CadetPeerPath *
GCC_get_path (const struct CadetConnection *c)
{
  if (GNUNET_NO == c->destroy)
    return c->path;
  return NULL;
}


/**
 * Get the connection state.
 *
 * @param c Connection to get the state from.
 *
 * @return state of the connection.
 */
enum CadetConnectionState
GCC_get_state (const struct CadetConnection *c)
{
  return c->state;
}

/**
 * Get the connection tunnel.
 *
 * @param c Connection to get the tunnel from.
 *
 * @return tunnel of the connection.
 */
struct CadetTunnel *
GCC_get_tunnel (const struct CadetConnection *c)
{
  return c->t;
}


/**
 * Get free buffer space in a connection.
 *
 * @param c Connection.
 * @param fwd Is query about FWD traffic?
 *
 * @return Free buffer space [0 - max_msgs_queue/max_connections]
 */
unsigned int
GCC_get_buffer (struct CadetConnection *c, int fwd)
{
  struct CadetFlowControl *fc;

  fc = fwd ? &c->fwd_fc : &c->bck_fc;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "  Get %s buffer on %s: %u - %u\n",
       GC_f2s (fwd), GCC_2s (c), fc->queue_max, fc->queue_n);
  GCC_debug (c, GNUNET_ERROR_TYPE_DEBUG);

  return (fc->queue_max - fc->queue_n);
}


/**
 * Get how many messages have we allowed to send to us from a direction.
 *
 * @param c Connection.
 * @param fwd Are we asking about traffic from FWD (BCK messages)?
 *
 * @return last_ack_sent - last_pid_recv
 */
unsigned int
GCC_get_allowed (struct CadetConnection *c, int fwd)
{
  struct CadetFlowControl *fc;

  fc = fwd ? &c->fwd_fc : &c->bck_fc;
  if (CADET_CONNECTION_READY != c->state
      || GC_is_pid_bigger (fc->last_pid_recv, fc->last_ack_sent))
  {
    return 0;
  }
  return (fc->last_ack_sent - fc->last_pid_recv);
}


/**
 * Get messages queued in a connection.
 *
 * @param c Connection.
 * @param fwd Is query about FWD traffic?
 *
 * @return Number of messages queued.
 */
unsigned int
GCC_get_qn (struct CadetConnection *c, int fwd)
{
  struct CadetFlowControl *fc;

  fc = fwd ? &c->fwd_fc : &c->bck_fc;

  return fc->queue_n;
}


/**
 * Get next PID to use.
 *
 * @param c Connection.
 * @param fwd Is query about FWD traffic?
 *
 * @return Last PID used + 1.
 */
unsigned int
GCC_get_pid (struct CadetConnection *c, int fwd)
{
  struct CadetFlowControl *fc;

  fc = fwd ? &c->fwd_fc : &c->bck_fc;

  return fc->last_pid_sent + 1;
}


/**
 * Allow the connection to advertise a buffer of the given size.
 *
 * The connection will send an @c fwd ACK message (so: in direction !fwd)
 * allowing up to last_pid_recv + buffer.
 *
 * @param c Connection.
 * @param buffer How many more messages the connection can accept.
 * @param fwd Is this about FWD traffic? (The ack will go dest->root).
 */
void
GCC_allow (struct CadetConnection *c, unsigned int buffer, int fwd)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowing %s %u messages %s\n",
       GCC_2s (c), buffer, GC_f2s (fwd));
  send_ack (c, buffer, fwd, GNUNET_NO);
}


/**
 * Notify other peers on a connection of a broken link. Mark connections
 * to destroy after all traffic has been sent.
 *
 * @param c Connection on which there has been a disconnection.
 * @param peer Peer that disconnected.
 */
void
GCC_neighbor_disconnected (struct CadetConnection *c, struct CadetPeer *peer)
{
  struct CadetPeer *hop;
  char peer_name[16];
  int fwd;

  GCC_check_connections ();
  strncpy (peer_name, GCP_2s (peer), 16);
  peer_name[15] = '\0';
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "shutting down %s, %s disconnected\n",
       GCC_2s (c), peer_name);
  hop = get_prev_hop (c);
  if (NULL == hop)
  {
    /* Path was NULL, we should have deleted the connection. */
    GNUNET_break (0);
    return;
  }
  fwd = (peer == hop);
  if ( (GNUNET_YES == GCC_is_terminal (c, fwd)) ||
       (GNUNET_NO != c->destroy) )
  {
    /* Local shutdown, or other peer already down (hence 'c->destroy');
       so there is no one to notify about this, just clean up. */
    GCC_destroy (c);
    GCC_check_connections ();
    return;
  }
  send_broken (c, &my_full_id, GCP_get_id (peer), fwd);
  /* Connection will have at least one pending message
   * (the one we just scheduled), so delay destruction
   * and remove from map so we don't use accidentally. */
  c->destroy = GNUNET_YES;
  c->state = CADET_CONNECTION_DESTROYED;
  GNUNET_assert (GNUNET_NO == c->was_removed);
  c->was_removed = GNUNET_YES;
  GNUNET_break (GNUNET_YES ==
                GNUNET_CONTAINER_multihashmap_remove (connections,
                                                      GCC_get_h (c),
                                                      c));
  /* Cancel queue in the direction that just died. */
  connection_cancel_queues (c, ! fwd);
  GCC_stop_poll (c, ! fwd);
  unregister_neighbors (c);
  GCC_check_connections ();
}


/**
 * Is this peer the first one on the connection?
 *
 * @param c Connection.
 * @param fwd Is this about fwd traffic?
 *
 * @return #GNUNET_YES if origin, #GNUNET_NO if relay/terminal.
 */
int
GCC_is_origin (struct CadetConnection *c, int fwd)
{
  if (!fwd && c->path->length - 1 == c->own_pos )
    return GNUNET_YES;
  if (fwd && 0 == c->own_pos)
    return GNUNET_YES;
  return GNUNET_NO;
}


/**
 * Is this peer the last one on the connection?
 *
 * @param c Connection.
 * @param fwd Is this about fwd traffic?
 *            Note that the ROOT is the terminal for BCK traffic!
 *
 * @return #GNUNET_YES if terminal, #GNUNET_NO if relay/origin.
 */
int
GCC_is_terminal (struct CadetConnection *c, int fwd)
{
  return GCC_is_origin (c, ! fwd);
}


/**
 * See if we are allowed to send by the next hop in the given direction.
 *
 * @param c Connection.
 * @param fwd Is this about fwd traffic?
 *
 * @return #GNUNET_YES in case it's OK to send.
 */
int
GCC_is_sendable (struct CadetConnection *c, int fwd)
{
  struct CadetFlowControl *fc;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       " checking sendability of %s traffic on %s\n",
       GC_f2s (fwd), GCC_2s (c));
  if (NULL == c)
  {
    GNUNET_break (0);
    return GNUNET_YES;
  }
  fc = fwd ? &c->fwd_fc : &c->bck_fc;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       " last ack recv: %u, last pid sent: %u\n",
       fc->last_ack_recv, fc->last_pid_sent);
  if (GC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, " sendable\n");
    return GNUNET_YES;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, " not sendable\n");
  return GNUNET_NO;
}


/**
 * Check if this connection is a direct one (never trim a direct connection).
 *
 * @param c Connection.
 *
 * @return #GNUNET_YES in case it's a direct connection, #GNUNET_NO otherwise.
 */
int
GCC_is_direct (struct CadetConnection *c)
{
  return (c->path->length == 2) ? GNUNET_YES : GNUNET_NO;
}


/**
 * Sends an already built message on a connection, properly registering
 * all used resources.
 *
 * @param message Message to send. Function makes a copy of it.
 *                If message is not hop-by-hop, decrements TTL of copy.
 * @param payload_type Type of payload, in case the message is encrypted.
 * @param c Connection on which this message is transmitted.
 * @param fwd Is this a fwd message?
 * @param force Force the connection to accept the message (buffer overfill).
 * @param cont Continuation called once message is sent. Can be NULL.
 * @param cont_cls Closure for @c cont.
 *
 * @return Handle to cancel the message before it's sent.
 *         NULL on error or if @c cont is NULL.
 *         Invalid on @c cont call.
 */
struct CadetConnectionQueue *
GCC_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
                           uint16_t payload_type, uint32_t payload_id,
                           struct CadetConnection *c, int fwd, int force,
                           GCC_sent cont, void *cont_cls)
{
  struct CadetFlowControl *fc;
  struct CadetConnectionQueue *q;
  void *data;
  size_t size;
  uint16_t type;
  int droppable;

  GCC_check_connections ();
  size = ntohs (message->size);
  data = GNUNET_malloc (size);
  memcpy (data, message, size);
  type = ntohs (message->type);
  LOG (GNUNET_ERROR_TYPE_INFO,
       "--> %s (%s %4u) on conn %s (%p) %s (%u bytes)\n",
       GC_m2s (type), GC_m2s (payload_type), payload_id, GCC_2s (c), c,
       GC_f2s(fwd), size);

  fc = fwd ? &c->fwd_fc : &c->bck_fc;
  droppable = GNUNET_NO == force;
  switch (type)
  {
    struct GNUNET_CADET_AX        *axmsg;
    struct GNUNET_CADET_Encrypted *emsg;
    struct GNUNET_CADET_KX        *kmsg;
    struct GNUNET_CADET_ACK       *amsg;
    struct GNUNET_CADET_Poll      *pmsg;
    struct GNUNET_CADET_ConnectionDestroy *dmsg;
    struct GNUNET_CADET_ConnectionBroken  *bmsg;
    uint32_t ttl;

    case GNUNET_MESSAGE_TYPE_CADET_AX:
    case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
      if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
      {
        emsg = (struct GNUNET_CADET_Encrypted *) data;
        ttl = ntohl (emsg->ttl);
        if (0 == ttl)
        {
          GNUNET_break_op (0);
          GNUNET_free (data);
          return NULL;
        }
        emsg->cid = c->id;
        emsg->ttl = htonl (ttl - 1);
      }
      else
      {
        axmsg = (struct GNUNET_CADET_AX *) data;
        axmsg->cid = c->id;
      }
      LOG (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
      LOG (GNUNET_ERROR_TYPE_DEBUG, "last pid sent %u\n", fc->last_pid_sent);
      LOG (GNUNET_ERROR_TYPE_DEBUG, "     ack recv %u\n", fc->last_ack_recv);
      if (GNUNET_YES == droppable)
      {
        fc->queue_n++;
      }
      else
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG, "  not droppable, Q_N stays the same\n");
      }
      break;

    case GNUNET_MESSAGE_TYPE_CADET_KX:
      kmsg = (struct GNUNET_CADET_KX *) data;
      kmsg->cid = c->id;
      break;

    case GNUNET_MESSAGE_TYPE_CADET_ACK:
      amsg = (struct GNUNET_CADET_ACK *) data;
      amsg->cid = c->id;
      LOG (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
      droppable = GNUNET_NO;
      break;

    case GNUNET_MESSAGE_TYPE_CADET_POLL:
      pmsg = (struct GNUNET_CADET_Poll *) data;
      pmsg->cid = c->id;
      LOG (GNUNET_ERROR_TYPE_DEBUG, " POLL %u\n", ntohl (pmsg->pid));
      droppable = GNUNET_NO;
      break;

    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
      dmsg = (struct GNUNET_CADET_ConnectionDestroy *) data;
      dmsg->cid = c->id;
      break;

    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
      bmsg = (struct GNUNET_CADET_ConnectionBroken *) data;
      bmsg->cid = c->id;
      break;

    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
      break;

    default:
      GNUNET_break (0);
      GNUNET_free (data);
      return NULL;
  }

  if (fc->queue_n > fc->queue_max && droppable)
  {
    GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
                              1, GNUNET_NO);
    GNUNET_break (0);
    LOG (GNUNET_ERROR_TYPE_DEBUG, "queue full: %u/%u\n",
         fc->queue_n, fc->queue_max);
    if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type
        || GNUNET_MESSAGE_TYPE_CADET_AX == type)
    {
      fc->queue_n--;
    }
    GNUNET_free (data);
    return NULL; /* Drop this message */
  }

  LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %s %u\n",
       GCC_2s (c), c->pending_messages);
  c->pending_messages++;

  q = GNUNET_new (struct CadetConnectionQueue);
  q->forced = !droppable;
  q->q = GCP_queue_add (get_hop (c, fwd), data, type, payload_type, payload_id,
                        size, c, fwd, &conn_message_sent, q);
  if (NULL == q->q)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "dropping msg on %s, NULL q\n", GCC_2s (c));
    GNUNET_free (data);
    GNUNET_free (q);
    GCC_check_connections ();
    return NULL;
  }
  q->cont = cont;
  q->cont_cls = cont_cls;
  GCC_check_connections ();
  return (NULL == cont) ? NULL : q;
}


/**
 * Cancel a previously sent message while it's in the queue.
 *
 * ONLY can be called before the continuation given to the send function
 * is called. Once the continuation is called, the message is no longer in the
 * queue.
 *
 * @param q Handle to the queue.
 */
void
GCC_cancel (struct CadetConnectionQueue *q)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG, "!  GCC cancel message\n");

  /* queue destroy calls message_sent, which calls q->cont and frees q */
  GCP_queue_destroy (q->q, GNUNET_YES, GNUNET_NO, 0);
  GCC_check_connections ();
}


/**
 * Sends a CREATE CONNECTION message for a path to a peer.
 * Changes the connection and tunnel states if necessary.
 *
 * @param connection Connection to create.
 */
void
GCC_send_create (struct CadetConnection *connection)
{
  enum CadetTunnelCState state;
  size_t size;

  GCC_check_connections ();
  size = sizeof (struct GNUNET_CADET_ConnectionCreate);
  size += connection->path->length * sizeof (struct GNUNET_PeerIdentity);

  LOG (GNUNET_ERROR_TYPE_INFO, "--> %s on conn %s  (%u bytes)\n",
       GC_m2s (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE),
       GCC_2s (connection), size);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u (create)\n",
       connection, connection->pending_messages);
  connection->pending_messages++;

  connection->maintenance_q =
    GCP_queue_add (get_next_hop (connection), NULL,
                   GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE, 0, 0,
                   size, connection, GNUNET_YES, &conn_message_sent, NULL);

  state = GCT_get_cstate (connection->t);
  if (CADET_TUNNEL_SEARCHING == state || CADET_TUNNEL_NEW == state)
    GCT_change_cstate (connection->t, CADET_TUNNEL_WAITING);
  if (CADET_CONNECTION_NEW == connection->state)
    connection_change_state (connection, CADET_CONNECTION_SENT);
  GCC_check_connections ();
}


/**
 * Send a message to all peers in this connection that the connection
 * is no longer valid.
 *
 * If some peer should not receive the message, it should be zero'ed out
 * before calling this function.
 *
 * @param c The connection whose peers to notify.
 */
void
GCC_send_destroy (struct CadetConnection *c)
{
  struct GNUNET_CADET_ConnectionDestroy msg;

  if (GNUNET_YES == c->destroy)
    return;
  GCC_check_connections ();
  msg.header.size = htons (sizeof (msg));
  msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY);
  msg.cid = c->id;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
              "  sending connection destroy for connection %s\n",
              GCC_2s (c));

  if (GNUNET_NO == GCC_is_terminal (c, GNUNET_YES))
    GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg.header, 0, 0, c,
                                                      GNUNET_YES, GNUNET_YES,
                                                      NULL, NULL));
  if (GNUNET_NO == GCC_is_terminal (c, GNUNET_NO))
    GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg.header, 0, 0, c,
                                                      GNUNET_NO, GNUNET_YES,
                                                      NULL, NULL));
  c->destroy = GNUNET_YES;
  c->state = CADET_CONNECTION_DESTROYED;
  GCC_check_connections ();
}


/**
 * @brief Start a polling timer for the connection.
 *
 * When a neighbor does not accept more traffic on the connection it could be
 * caused by a simple congestion or by a lost ACK. Polling enables to check
 * for the lastest ACK status for a connection.
 *
 * @param c Connection.
 * @param fwd Should we poll in the FWD direction?
 */
void
GCC_start_poll (struct CadetConnection *c, int fwd)
{
  struct CadetFlowControl *fc;

  fc = fwd ? &c->fwd_fc : &c->bck_fc;
  LOG (GNUNET_ERROR_TYPE_DEBUG, "POLL %s requested\n",
       GC_f2s (fwd));
  if (NULL != fc->poll_task || NULL != fc->poll_msg)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  POLL not needed (%p, %p)\n",
         fc->poll_task, fc->poll_msg);
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, "POLL started on request\n");
  fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
                                                &connection_poll,
                                                fc);
}


/**
 * @brief Stop polling a connection for ACKs.
 *
 * Once we have enough ACKs for future traffic, polls are no longer necessary.
 *
 * @param c Connection.
 * @param fwd Should we stop the poll in the FWD direction?
 */
void
GCC_stop_poll (struct CadetConnection *c, int fwd)
{
  struct CadetFlowControl *fc;

  fc = fwd ? &c->fwd_fc : &c->bck_fc;
  if (NULL != fc->poll_task)
  {
    GNUNET_SCHEDULER_cancel (fc->poll_task);
    fc->poll_task = NULL;
  }
}


/**
 * Get a (static) string for a connection.
 *
 * @param c Connection.
 */
const char *
GCC_2s (const struct CadetConnection *c)
{
  if (NULL == c)
    return "NULL";

  if (NULL != c->t)
  {
    static char buf[128];

    SPRINTF (buf, "%s (->%s)",
             GNUNET_h2s (GC_h2hc (GCC_get_id (c))), GCT_2s (c->t));
    return buf;
  }
  return GNUNET_h2s (GC_h2hc (&c->id));
}


/**
 * Log all possible info about the connection state.
 *
 * @param c Connection to debug.
 * @param level Debug level to use.
 */
void
GCC_debug (const struct CadetConnection *c, enum GNUNET_ErrorType level)
{
  int do_log;
  char *s;

  do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
                                       "cadet-con",
                                       __FILE__, __FUNCTION__, __LINE__);
  if (0 == do_log)
    return;

  if (NULL == c)
  {
    LOG2 (level, "CCC DEBUG NULL CONNECTION\n");
    return;
  }

  LOG2 (level, "CCC DEBUG CONNECTION %s\n", GCC_2s (c));
  s = path_2s (c->path);
  LOG2 (level, "CCC  path %s, own pos: %u\n", s, c->own_pos);
  GNUNET_free (s);
  LOG2 (level, "CCC  state: %s, destroy: %u\n",
        GCC_state2s (c->state), c->destroy);
  LOG2 (level, "CCC  pending messages: %u\n", c->pending_messages);
  if (NULL != c->perf)
    LOG2 (level, "CCC  us/byte: %f\n", c->perf->avg);

  LOG2 (level, "CCC  FWD flow control:\n");
  LOG2 (level, "CCC   queue: %u/%u\n", c->fwd_fc.queue_n, c->fwd_fc.queue_max);
  LOG2 (level, "CCC   last PID sent: %5u, recv: %5u\n",
        c->fwd_fc.last_pid_sent, c->fwd_fc.last_pid_recv);
  LOG2 (level, "CCC   last ACK sent: %5u, recv: %5u\n",
        c->fwd_fc.last_ack_sent, c->fwd_fc.last_ack_recv);
  LOG2 (level, "CCC   recv PID bitmap: %X\n", c->fwd_fc.recv_bitmap);
  LOG2 (level, "CCC   poll: task %d, msg  %p, msg_ack %p)\n",
        c->fwd_fc.poll_task, c->fwd_fc.poll_msg, c->fwd_fc.ack_msg);

  LOG2 (level, "CCC  BCK flow control:\n");
  LOG2 (level, "CCC   queue: %u/%u\n", c->bck_fc.queue_n, c->bck_fc.queue_max);
  LOG2 (level, "CCC   last PID sent: %5u, recv: %5u\n",
        c->bck_fc.last_pid_sent, c->bck_fc.last_pid_recv);
  LOG2 (level, "CCC   last ACK sent: %5u, recv: %5u\n",
        c->bck_fc.last_ack_sent, c->bck_fc.last_ack_recv);
  LOG2 (level, "CCC   recv PID bitmap: %X\n", c->bck_fc.recv_bitmap);
  LOG2 (level, "CCC   poll: task %d, msg  %p, msg_ack %p)\n",
        c->bck_fc.poll_task, c->bck_fc.poll_msg, c->bck_fc.ack_msg);

  LOG2 (level, "CCC DEBUG CONNECTION END\n");
}