aboutsummaryrefslogtreecommitdiff
path: root/src/cadet/gnunet-service-cadet_tunnels.c
blob: c1c511da106f7ce9013ac914861c6a992f338313 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
/*
     This file is part of GNUnet.
     Copyright (C) 2013, 2017, 2018 GNUnet e.V.

     GNUnet is free software: you can redistribute it and/or modify it
     under the terms of the GNU Affero General Public License as published
     by the Free Software Foundation, either version 3 of the License,
     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
     Affero General Public License for more details.

     You should have received a copy of the GNU Affero General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.

     SPDX-License-Identifier: AGPL3.0-or-later
 */
/**
 * @file cadet/gnunet-service-cadet_tunnels.c
 * @brief Information we track per tunnel.
 * @author Bartlomiej Polot
 * @author Christian Grothoff
 *
 * FIXME:
 * - proper connection evaluation during connection management:
 *   + consider quality (or quality spread?) of current connection set
 *     when deciding how often to do maintenance
 *   + interact with PEER to drive DHT GET/PUT operations based
 *     on how much we like our connections
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_statistics_service.h"
#include "gnunet_signatures.h"
#include "cadet_protocol.h"
#include "gnunet-service-cadet_channel.h"
#include "gnunet-service-cadet_connection.h"
#include "gnunet-service-cadet_tunnels.h"
#include "gnunet-service-cadet_peer.h"
#include "gnunet-service-cadet_paths.h"


#define LOG(level, ...) GNUNET_log_from (level, "cadet-tun", __VA_ARGS__)

/**
 * How often do we try to decrypt payload with unverified key
 * material?  Used to limit CPU increase upon receiving bogus
 * KX.
 */
#define MAX_UNVERIFIED_ATTEMPTS 16

/**
 * How long do we wait until tearing down an idle tunnel?
 */
#define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply ( \
    GNUNET_TIME_UNIT_SECONDS, 90)

/**
 * How long do we wait initially before retransmitting the KX?
 * TODO: replace by 2 RTT if/once we have connection-level RTT data!
 */
#define INITIAL_KX_RETRY_DELAY GNUNET_TIME_relative_multiply ( \
    GNUNET_TIME_UNIT_MILLISECONDS, 250)

/**
 * Maximum number of skipped keys we keep in memory per tunnel.
 */
#define MAX_SKIPPED_KEYS 64

/**
 * Maximum number of keys (and thus ratchet steps) we are willing to
 * skip before we decide this is either a bogus packet or a DoS-attempt.
 */
#define MAX_KEY_GAP 256


/**
 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
 */
struct CadetTunnelSkippedKey
{
  /**
   * DLL next.
   */
  struct CadetTunnelSkippedKey *next;

  /**
   * DLL prev.
   */
  struct CadetTunnelSkippedKey *prev;

  /**
   * When was this key stored (for timeout).
   */
  struct GNUNET_TIME_Absolute timestamp;

  /**
   * Header key.
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey HK;

  /**
   * Message key.
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey MK;

  /**
   * Key number for a given HK.
   */
  unsigned int Kn;
};


/**
 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
 */
struct CadetTunnelAxolotl
{
  /**
   * A (double linked) list of stored message keys and associated header keys
   * for "skipped" messages, i.e. messages that have not been
   * received despite the reception of more recent messages, (head).
   */
  struct CadetTunnelSkippedKey *skipped_head;

  /**
   * Skipped messages' keys DLL, tail.
   */
  struct CadetTunnelSkippedKey *skipped_tail;

  /**
   * 32-byte root key which gets updated by DH ratchet.
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey RK;

  /**
   * 32-byte header key (currently used for sending).
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey HKs;

  /**
   * 32-byte header key (currently used for receiving)
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey HKr;

  /**
   * 32-byte next header key (for sending), used once the
   * ratchet advances.  We are sure that the sender has this
   * key as well only after @e ratchet_allowed is #GNUNET_YES.
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;

  /**
   * 32-byte next header key (for receiving).  To be tried
   * when decrypting with @e HKr fails and thus the sender
   * may have advanced the ratchet.
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;

  /**
   * 32-byte chain keys (used for forward-secrecy) for
   * sending messages. Updated for every message.
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey CKs;

  /**
   * 32-byte chain keys (used for forward-secrecy) for
   * receiving messages. Updated for every message. If
   * messages are skipped, the respective derived MKs
   * (and the current @HKr) are kept in the @e skipped_head DLL.
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey CKr;

  /**
   * ECDH for key exchange (A0 / B0).
   */
  struct GNUNET_CRYPTO_EcdhePrivateKey kx_0;

  /**
   * ECDH Ratchet key (our private key in the current DH).
   */
  struct GNUNET_CRYPTO_EcdhePrivateKey DHRs;

  /**
   * ECDH Ratchet key (other peer's public key in the current DH).
   */
  struct GNUNET_CRYPTO_EcdhePublicKey DHRr;

  /**
   * Last ephemeral public key received from the other peer,
   * for duplicate detection.
   */
  struct GNUNET_CRYPTO_EcdhePublicKey last_ephemeral;

  /**
   * Time when the current ratchet expires and a new one is triggered
   * (if @e ratchet_allowed is #GNUNET_YES).
   */
  struct GNUNET_TIME_Absolute ratchet_expiration;

  /**
   * Number of elements in @a skipped_head <-> @a skipped_tail.
   */
  unsigned int skipped;

  /**
   * Message number (reset to 0 with each new ratchet, next message to send).
   */
  uint32_t Ns;

  /**
   * Message number (reset to 0 with each new ratchet, next message to recv).
   */
  uint32_t Nr;

  /**
   * Previous message numbers (# of msgs sent under prev ratchet)
   */
  uint32_t PNs;

  /**
   * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
   */
  int ratchet_flag;

  /**
   * True (#GNUNET_YES) if we have received a message from the
   * other peer that uses the keys from our last ratchet step.
   * This implies that we are again allowed to advance the ratchet,
   * otherwise we have to wait until the other peer sees our current
   * ephemeral key and advances first.
   *
   * #GNUNET_NO if we have advanced the ratched but lack any evidence
   * that the other peer has noticed this.
   */
  int ratchet_allowed;

  /**
   * Number of messages recieved since our last ratchet advance.
   *
   * If this counter = 0, we cannot send a new ratchet key in the next
   * message.
   *
   * If this counter > 0, we could (but don't have to) send a new key.
   *
   * Once the @e ratchet_counter is larger than
   * #ratchet_messages (or @e ratchet_expiration time has past), and
   * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
   */
  unsigned int ratchet_counter;
};


/**
 * Struct used to save messages in a non-ready tunnel to send once connected.
 */
struct CadetTunnelQueueEntry
{
  /**
   * We are entries in a DLL
   */
  struct CadetTunnelQueueEntry *next;

  /**
   * We are entries in a DLL
   */
  struct CadetTunnelQueueEntry *prev;

  /**
   * Tunnel these messages belong in.
   */
  struct CadetTunnel *t;

  /**
   * Continuation to call once sent (on the channel layer).
   */
  GCT_SendContinuation cont;

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

  /**
   * Envelope of message to send follows.
   */
  struct GNUNET_MQ_Envelope *env;

  /**
   * Where to put the connection identifier into the payload
   * of the message in @e env once we have it?
   */
  struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
};


/**
 * Struct containing all information regarding a tunnel to a peer.
 */
struct CadetTunnel
{
  /**
   * Destination of the tunnel.
   */
  struct CadetPeer *destination;

  /**
   * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
   * ephemeral key changes.
   */
  struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;

  /**
   * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey e_key;

  /**
   * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey d_key;

  /**
   * Axolotl info.
   */
  struct CadetTunnelAxolotl ax;

  /**
   * Unverified Axolotl info, used only if we got a fresh KX (not a
   * KX_AUTH) while our end of the tunnel was still up.  In this case,
   * we keep the fresh KX around but do not put it into action until
   * we got encrypted payload that assures us of the authenticity of
   * the KX.
   */
  struct CadetTunnelAxolotl *unverified_ax;

  /**
   * Task scheduled if there are no more channels using the tunnel.
   */
  struct GNUNET_SCHEDULER_Task *destroy_task;

  /**
   * Task to trim connections if too many are present.
   */
  struct GNUNET_SCHEDULER_Task *maintain_connections_task;

  /**
   * Task to send messages from queue (if possible).
   */
  struct GNUNET_SCHEDULER_Task *send_task;

  /**
   * Task to trigger KX.
   */
  struct GNUNET_SCHEDULER_Task *kx_task;

  /**
   * Tokenizer for decrypted messages.
   */
  struct GNUNET_MessageStreamTokenizer *mst;

  /**
   * Dispatcher for decrypted messages only (do NOT use for sending!).
   */
  struct GNUNET_MQ_Handle *mq;

  /**
   * DLL of ready connections that are actively used to reach the destination peer.
   */
  struct CadetTConnection *connection_ready_head;

  /**
   * DLL of ready connections that are actively used to reach the destination peer.
   */
  struct CadetTConnection *connection_ready_tail;

  /**
   * DLL of connections that we maintain that might be used to reach the destination peer.
   */
  struct CadetTConnection *connection_busy_head;

  /**
   * DLL of connections that we maintain that might be used to reach the destination peer.
   */
  struct CadetTConnection *connection_busy_tail;

  /**
   * Channels inside this tunnel. Maps
   * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
   */
  struct GNUNET_CONTAINER_MultiHashMap32 *channels;

  /**
   * Channel ID for the next created channel in this tunnel.
   */
  struct GNUNET_CADET_ChannelTunnelNumber next_ctn;

  /**
   * Queued messages, to transmit once tunnel gets connected.
   */
  struct CadetTunnelQueueEntry *tq_head;

  /**
   * Queued messages, to transmit once tunnel gets connected.
   */
  struct CadetTunnelQueueEntry *tq_tail;

  /**
   * Identification of the connection from which we are currently processing
   * a message. Only valid (non-NULL) during #handle_decrypted() and the
   * handle-*()-functions called from our @e mq during that function.
   */
  struct CadetTConnection *current_ct;

  /**
   * How long do we wait until we retry the KX?
   */
  struct GNUNET_TIME_Relative kx_retry_delay;

  /**
   * When do we try the next KX?
   */
  struct GNUNET_TIME_Absolute next_kx_attempt;

  /**
   * Number of connections in the @e connection_ready_head DLL.
   */
  unsigned int num_ready_connections;

  /**
   * Number of connections in the @e connection_busy_head DLL.
   */
  unsigned int num_busy_connections;

  /**
   * How often have we tried and failed to decrypt a message using
   * the unverified KX material from @e unverified_ax?  Used to
   * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
   */
  unsigned int unverified_attempts;

  /**
   * Number of entries in the @e tq_head DLL.
   */
  unsigned int tq_len;

  /**
   * State of the tunnel encryption.
   */
  enum CadetTunnelEState estate;

  /**
   * Force triggering KX_AUTH independent of @e estate.
   */
  int kx_auth_requested;
};


/**
 * Am I Alice or Betty (some call her Bob), or talking to myself?
 *
 * @param other the other peer
 * @return #GNUNET_YES for Alice, #GNUNET_NO for Betty, #GNUNET_SYSERR if talking to myself
 */
int
GCT_alice_or_betty (const struct GNUNET_PeerIdentity *other)
{
  if (0 > GNUNET_memcmp (&my_full_id,
                         other))
    return GNUNET_YES;
  else if (0 < GNUNET_memcmp (&my_full_id,
                              other))
    return GNUNET_NO;
  else
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
}


/**
 * Connection @a ct is now unready, clear it's ready flag
 * and move it from the ready DLL to the busy DLL.
 *
 * @param ct connection to move to unready status
 */
static void
mark_connection_unready (struct CadetTConnection *ct)
{
  struct CadetTunnel *t = ct->t;

  GNUNET_assert (GNUNET_YES == ct->is_ready);
  GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
                               t->connection_ready_tail,
                               ct);
  GNUNET_assert (0 < t->num_ready_connections);
  t->num_ready_connections--;
  ct->is_ready = GNUNET_NO;
  GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
                               t->connection_busy_tail,
                               ct);
  t->num_busy_connections++;
}


/**
 * Get the static string for the peer this tunnel is directed.
 *
 * @param t Tunnel.
 *
 * @return Static string the destination peer's ID.
 */
const char *
GCT_2s (const struct CadetTunnel *t)
{
  static char buf[64];

  if (NULL == t)
    return "Tunnel(NULL)";
  GNUNET_snprintf (buf,
                   sizeof(buf),
                   "Tunnel %s",
                   GNUNET_i2s (GCP_get_id (t->destination)));
  return buf;
}


/**
 * Get string description for tunnel encryption state.
 *
 * @param es Tunnel state.
 *
 * @return String representation.
 */
static const char *
estate2s (enum CadetTunnelEState es)
{
  static char buf[32];

  switch (es)
  {
  case CADET_TUNNEL_KEY_UNINITIALIZED:
    return "CADET_TUNNEL_KEY_UNINITIALIZED";
  case CADET_TUNNEL_KEY_AX_RECV:
    return "CADET_TUNNEL_KEY_AX_RECV";
  case CADET_TUNNEL_KEY_AX_SENT:
    return "CADET_TUNNEL_KEY_AX_SENT";
  case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
    return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
  case CADET_TUNNEL_KEY_AX_AUTH_SENT:
    return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
  case CADET_TUNNEL_KEY_OK:
    return "CADET_TUNNEL_KEY_OK";
  }
  GNUNET_snprintf (buf,
                   sizeof(buf),
                   "%u (UNKNOWN STATE)",
                   es);
  return buf;
}


/**
 * Return the peer to which this tunnel goes.
 *
 * @param t a tunnel
 * @return the destination of the tunnel
 */
struct CadetPeer *
GCT_get_destination (struct CadetTunnel *t)
{
  return t->destination;
}


/**
 * Count channels of a tunnel.
 *
 * @param t Tunnel on which to count.
 *
 * @return Number of channels.
 */
unsigned int
GCT_count_channels (struct CadetTunnel *t)
{
  return GNUNET_CONTAINER_multihashmap32_size (t->channels);
}


/**
 * Lookup a channel by its @a ctn.
 *
 * @param t tunnel to look in
 * @param ctn number of channel to find
 * @return NULL if channel does not exist
 */
struct CadetChannel *
lookup_channel (struct CadetTunnel *t,
                struct GNUNET_CADET_ChannelTunnelNumber ctn)
{
  return GNUNET_CONTAINER_multihashmap32_get (t->channels,
                                              ntohl (ctn.cn));
}


/**
 * Count all created connections of a tunnel. Not necessarily ready connections!
 *
 * @param t Tunnel on which to count.
 *
 * @return Number of connections created, either being established or ready.
 */
unsigned int
GCT_count_any_connections (const struct CadetTunnel *t)
{
  return t->num_ready_connections + t->num_busy_connections;
}


/**
 * Find first connection that is ready in the list of
 * our connections.  Picks ready connections round-robin.
 *
 * @param t tunnel to search
 * @return NULL if we have no connection that is ready
 */
static struct CadetTConnection *
get_ready_connection (struct CadetTunnel *t)
{
  struct CadetTConnection *hd = t->connection_ready_head;

  GNUNET_assert ((NULL == hd) ||
                 (GNUNET_YES == hd->is_ready));
  return hd;
}


/**
 * Get the encryption state of a tunnel.
 *
 * @param t Tunnel.
 *
 * @return Tunnel's encryption state.
 */
enum CadetTunnelEState
GCT_get_estate (struct CadetTunnel *t)
{
  return t->estate;
}


/**
 * Called when either we have a new connection, or a new message in the
 * queue, or some existing connection has transmission capacity.  Looks
 * at our message queue and if there is a message, picks a connection
 * to send it on.
 *
 * @param cls the `struct CadetTunnel` to process messages on
 */
static void
trigger_transmissions (void *cls);


/* ************************************** start core crypto ***************************** */


/**
 * Create a new Axolotl ephemeral (ratchet) key.
 *
 * @param ax key material to update
 */
static void
new_ephemeral (struct CadetTunnelAxolotl *ax)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Creating new ephemeral ratchet key (DHRs)\n");
  GNUNET_CRYPTO_ecdhe_key_create (&ax->DHRs);
}


/**
 * Calculate HMAC.
 *
 * @param plaintext Content to HMAC.
 * @param size Size of @c plaintext.
 * @param iv Initialization vector for the message.
 * @param key Key to use.
 * @param hmac[out] Destination to store the HMAC.
 */
static void
t_hmac (const void *plaintext,
        size_t size,
        uint32_t iv,
        const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
        struct GNUNET_ShortHashCode *hmac)
{
  static const char ctx[] = "cadet authentication key";
  struct GNUNET_CRYPTO_AuthKey auth_key;
  struct GNUNET_HashCode hash;

  GNUNET_CRYPTO_hmac_derive_key (&auth_key,
                                 key,
                                 &iv, sizeof(iv),
                                 key, sizeof(*key),
                                 ctx, sizeof(ctx),
                                 NULL);
  /* Two step: GNUNET_ShortHash is only 256 bits,
     GNUNET_HashCode is 512, so we truncate. */
  GNUNET_CRYPTO_hmac (&auth_key,
                      plaintext,
                      size,
                      &hash);
  GNUNET_memcpy (hmac,
                 &hash,
                 sizeof(*hmac));
}


/**
 * Perform a HMAC.
 *
 * @param key Key to use.
 * @param[out] hash Resulting HMAC.
 * @param source Source key material (data to HMAC).
 * @param len Length of @a source.
 */
static void
t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
                struct GNUNET_HashCode *hash,
                const void *source,
                unsigned int len)
{
  static const char ctx[] = "axolotl HMAC-HASH";
  struct GNUNET_CRYPTO_AuthKey auth_key;

  GNUNET_CRYPTO_hmac_derive_key (&auth_key,
                                 key,
                                 ctx, sizeof(ctx),
                                 NULL);
  GNUNET_CRYPTO_hmac (&auth_key,
                      source,
                      len,
                      hash);
}


/**
 * Derive a symmetric encryption key from an HMAC-HASH.
 *
 * @param key Key to use for the HMAC.
 * @param[out] out Key to generate.
 * @param source Source key material (data to HMAC).
 * @param len Length of @a source.
 */
static void
t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
                   struct GNUNET_CRYPTO_SymmetricSessionKey *out,
                   const void *source,
                   unsigned int len)
{
  static const char ctx[] = "axolotl derive key";
  struct GNUNET_HashCode h;

  t_ax_hmac_hash (key,
                  &h,
                  source,
                  len);
  GNUNET_CRYPTO_kdf (out, sizeof(*out),
                     ctx, sizeof(ctx),
                     &h, sizeof(h),
                     NULL);
}


/**
 * Encrypt data with the axolotl tunnel key.
 *
 * @param ax key material to use.
 * @param dst Destination with @a size bytes for the encrypted data.
 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
 * @param size Size of the buffers at @a src and @a dst
 */
static void
t_ax_encrypt (struct CadetTunnelAxolotl *ax,
              void *dst,
              const void *src,
              size_t size)
{
  struct GNUNET_CRYPTO_SymmetricSessionKey MK;
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  size_t out_size;

  ax->ratchet_counter++;
  if ((GNUNET_YES == ax->ratchet_allowed) &&
      ((ratchet_messages <= ax->ratchet_counter) ||
       (0 == GNUNET_TIME_absolute_get_remaining (
          ax->ratchet_expiration).rel_value_us)))
  {
    ax->ratchet_flag = GNUNET_YES;
  }
  if (GNUNET_YES == ax->ratchet_flag)
  {
    /* Advance ratchet */
    struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
    struct GNUNET_HashCode dh;
    struct GNUNET_HashCode hmac;
    static const char ctx[] = "axolotl ratchet";

    new_ephemeral (ax);
    ax->HKs = ax->NHKs;

    /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
    GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
                            &ax->DHRr,
                            &dh);
    t_ax_hmac_hash (&ax->RK,
                    &hmac,
                    &dh,
                    sizeof(dh));
    GNUNET_CRYPTO_kdf (keys, sizeof(keys),
                       ctx, sizeof(ctx),
                       &hmac, sizeof(hmac),
                       NULL);
    ax->RK = keys[0];
    ax->NHKs = keys[1];
    ax->CKs = keys[2];

    ax->PNs = ax->Ns;
    ax->Ns = 0;
    ax->ratchet_flag = GNUNET_NO;
    ax->ratchet_allowed = GNUNET_NO;
    ax->ratchet_counter = 0;
    ax->ratchet_expiration
      = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
                                  ratchet_time);
  }

  t_hmac_derive_key (&ax->CKs,
                     &MK,
                     "0",
                     1);
  GNUNET_CRYPTO_symmetric_derive_iv (&iv,
                                     &MK,
                                     NULL, 0,
                                     NULL);

  out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
                                              size,
                                              &MK,
                                              &iv,
                                              dst);
  GNUNET_assert (size == out_size);
  t_hmac_derive_key (&ax->CKs,
                     &ax->CKs,
                     "1",
                     1);
}


/**
 * Decrypt data with the axolotl tunnel key.
 *
 * @param ax key material to use.
 * @param dst Destination for the decrypted data, must contain @a size bytes.
 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
 * @param size Size of the @a src and @a dst buffers
 */
static void
t_ax_decrypt (struct CadetTunnelAxolotl *ax,
              void *dst,
              const void *src,
              size_t size)
{
  struct GNUNET_CRYPTO_SymmetricSessionKey MK;
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  size_t out_size;

  t_hmac_derive_key (&ax->CKr,
                     &MK,
                     "0",
                     1);
  GNUNET_CRYPTO_symmetric_derive_iv (&iv,
                                     &MK,
                                     NULL, 0,
                                     NULL);
  GNUNET_assert (size >= sizeof(struct GNUNET_MessageHeader));
  out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
                                              size,
                                              &MK,
                                              &iv,
                                              dst);
  GNUNET_assert (out_size == size);
  t_hmac_derive_key (&ax->CKr,
                     &ax->CKr,
                     "1",
                     1);
}


/**
 * Encrypt header with the axolotl header key.
 *
 * @param ax key material to use.
 * @param[in|out] msg Message whose header to encrypt.
 */
static void
t_h_encrypt (struct CadetTunnelAxolotl *ax,
             struct GNUNET_CADET_TunnelEncryptedMessage *msg)
{
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  size_t out_size;

  GNUNET_CRYPTO_symmetric_derive_iv (&iv,
                                     &ax->HKs,
                                     NULL, 0,
                                     NULL);
  out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
                                              sizeof(struct
                                                     GNUNET_CADET_AxHeader),
                                              &ax->HKs,
                                              &iv,
                                              &msg->ax_header);
  GNUNET_assert (sizeof(struct GNUNET_CADET_AxHeader) == out_size);
}


/**
 * Decrypt header with the current axolotl header key.
 *
 * @param ax key material to use.
 * @param src Message whose header to decrypt.
 * @param dst Where to decrypt header to.
 */
static void
t_h_decrypt (struct CadetTunnelAxolotl *ax,
             const struct GNUNET_CADET_TunnelEncryptedMessage *src,
             struct GNUNET_CADET_TunnelEncryptedMessage *dst)
{
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  size_t out_size;

  GNUNET_CRYPTO_symmetric_derive_iv (&iv,
                                     &ax->HKr,
                                     NULL, 0,
                                     NULL);
  out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
                                              sizeof(struct
                                                     GNUNET_CADET_AxHeader),
                                              &ax->HKr,
                                              &iv,
                                              &dst->ax_header.Ns);
  GNUNET_assert (sizeof(struct GNUNET_CADET_AxHeader) == out_size);
}


/**
 * Delete a key from the list of skipped keys.
 *
 * @param ax key material to delete @a key from.
 * @param key Key to delete.
 */
static void
delete_skipped_key (struct CadetTunnelAxolotl *ax,
                    struct CadetTunnelSkippedKey *key)
{
  GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
                               ax->skipped_tail,
                               key);
  GNUNET_free (key);
  ax->skipped--;
}


/**
 * Decrypt and verify data with the appropriate tunnel key and verify that the
 * data has not been altered since it was sent by the remote peer.
 *
 * @param ax key material to use.
 * @param dst Destination for the plaintext.
 * @param src Source of the message. Can overlap with @c dst.
 * @param size Size of the message.
 * @return Size of the decrypted data, -1 if an error was encountered.
 */
static ssize_t
try_old_ax_keys (struct CadetTunnelAxolotl *ax,
                 void *dst,
                 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
                 size_t size)
{
  struct CadetTunnelSkippedKey *key;
  struct GNUNET_ShortHashCode *hmac;
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
  struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
  size_t esize;
  size_t res;
  size_t len;
  unsigned int N;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Trying skipped keys\n");
  hmac = &plaintext_header.hmac;
  esize = size - sizeof(struct GNUNET_CADET_TunnelEncryptedMessage);

  /* Find a correct Header Key */
  valid_HK = NULL;
  for (key = ax->skipped_head; NULL != key; key = key->next)
  {
    t_hmac (&src->ax_header,
            sizeof(struct GNUNET_CADET_AxHeader) + esize,
            0,
            &key->HK,
            hmac);
    if (0 == GNUNET_memcmp (hmac,
                            &src->hmac))
    {
      valid_HK = &key->HK;
      break;
    }
  }
  if (NULL == key)
    return -1;

  /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
  GNUNET_assert (size > sizeof(struct GNUNET_CADET_TunnelEncryptedMessage));
  len = size - sizeof(struct GNUNET_CADET_TunnelEncryptedMessage);
  GNUNET_assert (len >= sizeof(struct GNUNET_MessageHeader));

  /* Decrypt header */
  GNUNET_CRYPTO_symmetric_derive_iv (&iv,
                                     &key->HK,
                                     NULL, 0,
                                     NULL);
  res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
                                         sizeof(struct GNUNET_CADET_AxHeader),
                                         &key->HK,
                                         &iv,
                                         &plaintext_header.ax_header.Ns);
  GNUNET_assert (sizeof(struct GNUNET_CADET_AxHeader) == res);

  /* Find the correct message key */
  N = ntohl (plaintext_header.ax_header.Ns);
  while ((NULL != key) &&
         (N != key->Kn))
    key = key->next;
  if ((NULL == key) ||
      (0 != GNUNET_memcmp (&key->HK,
                           valid_HK)))
    return -1;

  /* Decrypt payload */
  GNUNET_CRYPTO_symmetric_derive_iv (&iv,
                                     &key->MK,
                                     NULL,
                                     0,
                                     NULL);
  res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
                                         len,
                                         &key->MK,
                                         &iv,
                                         dst);
  delete_skipped_key (ax,
                      key);
  return res;
}


/**
 * Delete a key from the list of skipped keys.
 *
 * @param ax key material to delete from.
 * @param HKr Header Key to use.
 */
static void
store_skipped_key (struct CadetTunnelAxolotl *ax,
                   const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
{
  struct CadetTunnelSkippedKey *key;

  key = GNUNET_new (struct CadetTunnelSkippedKey);
  key->timestamp = GNUNET_TIME_absolute_get ();
  key->Kn = ax->Nr;
  key->HK = ax->HKr;
  t_hmac_derive_key (&ax->CKr,
                     &key->MK,
                     "0",
                     1);
  t_hmac_derive_key (&ax->CKr,
                     &ax->CKr,
                     "1",
                     1);
  GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
                               ax->skipped_tail,
                               key);
  ax->skipped++;
  ax->Nr++;
}


/**
 * Stage skipped AX keys and calculate the message key.
 * Stores each HK and MK for skipped messages.
 *
 * @param ax key material to use
 * @param HKr Header key.
 * @param Np Received meesage number.
 * @return #GNUNET_OK if keys were stored.
 *         #GNUNET_SYSERR if an error ocurred (@a Np not expected).
 */
static int
store_ax_keys (struct CadetTunnelAxolotl *ax,
               const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
               uint32_t Np)
{
  int gap;

  gap = Np - ax->Nr;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Storing skipped keys [%u, %u)\n",
       ax->Nr,
       Np);
  if (MAX_KEY_GAP < gap)
  {
    /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
    /* TODO: start new key exchange on return */
    GNUNET_break_op (0);
    LOG (GNUNET_ERROR_TYPE_WARNING,
         "Got message %u, expected %u+\n",
         Np,
         ax->Nr);
    return GNUNET_SYSERR;
  }
  if (0 > gap)
  {
    /* Delayed message: don't store keys, flag to try old keys. */
    return GNUNET_SYSERR;
  }

  while (ax->Nr < Np)
    store_skipped_key (ax,
                       HKr);

  while (ax->skipped > MAX_SKIPPED_KEYS)
    delete_skipped_key (ax,
                        ax->skipped_tail);
  return GNUNET_OK;
}


/**
 * Decrypt and verify data with the appropriate tunnel key and verify that the
 * data has not been altered since it was sent by the remote peer.
 *
 * @param ax key material to use
 * @param dst Destination for the plaintext.
 * @param src Source of the message. Can overlap with @c dst.
 * @param size Size of the message.
 * @return Size of the decrypted data, -1 if an error was encountered.
 */
static ssize_t
t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
                           void *dst,
                           const struct
                           GNUNET_CADET_TunnelEncryptedMessage *src,
                           size_t size)
{
  struct GNUNET_ShortHashCode msg_hmac;
  struct GNUNET_HashCode hmac;
  struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
  uint32_t Np;
  uint32_t PNp;
  size_t esize; /* Size of encryped payload */

  esize = size - sizeof(struct GNUNET_CADET_TunnelEncryptedMessage);

  /* Try current HK */
  t_hmac (&src->ax_header,
          sizeof(struct GNUNET_CADET_AxHeader) + esize,
          0, &ax->HKr,
          &msg_hmac);
  if (0 != GNUNET_memcmp (&msg_hmac,
                          &src->hmac))
  {
    static const char ctx[] = "axolotl ratchet";
    struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];   /* RKp, NHKp, CKp */
    struct GNUNET_CRYPTO_SymmetricSessionKey HK;
    struct GNUNET_HashCode dh;
    struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;

    /* Try Next HK */
    t_hmac (&src->ax_header,
            sizeof(struct GNUNET_CADET_AxHeader) + esize,
            0,
            &ax->NHKr,
            &msg_hmac);
    if (0 != GNUNET_memcmp (&msg_hmac,
                            &src->hmac))
    {
      /* Try the skipped keys, if that fails, we're out of luck. */
      return try_old_ax_keys (ax,
                              dst,
                              src,
                              size);
    }
    HK = ax->HKr;
    ax->HKr = ax->NHKr;
    t_h_decrypt (ax,
                 src,
                 &plaintext_header);
    Np = ntohl (plaintext_header.ax_header.Ns);
    PNp = ntohl (plaintext_header.ax_header.PNs);
    DHRp = &plaintext_header.ax_header.DHRs;
    store_ax_keys (ax,
                   &HK,
                   PNp);

    /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
    GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
                            DHRp,
                            &dh);
    t_ax_hmac_hash (&ax->RK,
                    &hmac,
                    &dh, sizeof(dh));
    GNUNET_CRYPTO_kdf (keys, sizeof(keys),
                       ctx, sizeof(ctx),
                       &hmac, sizeof(hmac),
                       NULL);

    /* Commit "purported" keys */
    ax->RK = keys[0];
    ax->NHKr = keys[1];
    ax->CKr = keys[2];
    ax->DHRr = *DHRp;
    ax->Nr = 0;
    ax->ratchet_allowed = GNUNET_YES;
  }
  else
  {
    t_h_decrypt (ax,
                 src,
                 &plaintext_header);
    Np = ntohl (plaintext_header.ax_header.Ns);
    PNp = ntohl (plaintext_header.ax_header.PNs);
  }
  if ((Np != ax->Nr) &&
      (GNUNET_OK != store_ax_keys (ax,
                                   &ax->HKr,
                                   Np)))
  {
    /* Try the skipped keys, if that fails, we're out of luck. */
    return try_old_ax_keys (ax,
                            dst,
                            src,
                            size);
  }

  t_ax_decrypt (ax,
                dst,
                &src[1],
                esize);
  ax->Nr = Np + 1;
  return esize;
}


/**
 * Our tunnel became ready for the first time, notify channels
 * that have been waiting.
 *
 * @param cls our tunnel, not used
 * @param key unique ID of the channel, not used
 * @param value the `struct CadetChannel` to notify
 * @return #GNUNET_OK (continue to iterate)
 */
static int
notify_tunnel_up_cb (void *cls,
                     uint32_t key,
                     void *value)
{
  struct CadetChannel *ch = value;

  GCCH_tunnel_up (ch);
  return GNUNET_OK;
}


/**
 * Change the tunnel encryption state.
 * If the encryption state changes to OK, stop the rekey task.
 *
 * @param t Tunnel whose encryption state to change, or NULL.
 * @param state New encryption state.
 */
void
GCT_change_estate (struct CadetTunnel *t,
                   enum CadetTunnelEState state)
{
  enum CadetTunnelEState old = t->estate;

  t->estate = state;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s estate changed from %s to %s\n",
       GCT_2s (t),
       estate2s (old),
       estate2s (state));

  if ((CADET_TUNNEL_KEY_OK != old) &&
      (CADET_TUNNEL_KEY_OK == t->estate))
  {
    if (NULL != t->kx_task)
    {
      GNUNET_SCHEDULER_cancel (t->kx_task);
      t->kx_task = NULL;
    }
    /* notify all channels that have been waiting */
    GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
                                             &notify_tunnel_up_cb,
                                             t);
    if (NULL != t->send_task)
      GNUNET_SCHEDULER_cancel (t->send_task);
    t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
                                             t);
  }
}


/**
 * Send a KX message.
 *
 * @param t tunnel on which to send the KX_AUTH
 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
 *           we are to find one that is ready.
 * @param ax axolotl key context to use
 */
static void
send_kx (struct CadetTunnel *t,
         struct CadetTConnection *ct,
         struct CadetTunnelAxolotl *ax)
{
  struct CadetConnection *cc;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
  enum GNUNET_CADET_KX_Flags flags;

  if (GNUNET_YES != GCT_alice_or_betty (GCP_get_id (t->destination)))
    return; /* only Alice may send KX */
  if ((NULL == ct) ||
      (GNUNET_NO == ct->is_ready))
    ct = get_ready_connection (t);
  if (NULL == ct)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Wanted to send %s in state %s, but no connection is ready, deferring\n",
         GCT_2s (t),
         estate2s (t->estate));
    t->next_kx_attempt = GNUNET_TIME_absolute_get ();
    return;
  }
  cc = ct->cc;
  env = GNUNET_MQ_msg (msg,
                       GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
  flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
  msg->flags = htonl (flags);
  msg->cid = *GCC_get_id (cc);
  GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
                                      &msg->ephemeral_key);
#if DEBUG_KX
  msg->ephemeral_key_XXX = ax->kx_0;
  msg->private_key_XXX = *my_private_key;
#endif
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Sending KX message to %s with ephemeral %s on CID %s\n",
       GCT_2s (t),
       GNUNET_e2s (&msg->ephemeral_key),
       GNUNET_sh2s (&msg->cid.connection_of_tunnel));
  GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
                                      &msg->ratchet_key);
  mark_connection_unready (ct);
  t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
  t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
  if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
    GCT_change_estate (t,
                       CADET_TUNNEL_KEY_AX_SENT);
  else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
    GCT_change_estate (t,
                       CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
  GCC_transmit (cc,
                env);
  GNUNET_STATISTICS_update (stats,
                            "# KX transmitted",
                            1,
                            GNUNET_NO);
}


/**
 * Send a KX_AUTH message.
 *
 * @param t tunnel on which to send the KX_AUTH
 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
 *           we are to find one that is ready.
 * @param ax axolotl key context to use
 * @param force_reply Force the other peer to reply with a KX_AUTH message
 *         (set if we would like to transmit right now, but cannot)
 */
static void
send_kx_auth (struct CadetTunnel *t,
              struct CadetTConnection *ct,
              struct CadetTunnelAxolotl *ax,
              int force_reply)
{
  struct CadetConnection *cc;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
  enum GNUNET_CADET_KX_Flags flags;

  if ((NULL == ct) ||
      (GNUNET_NO == ct->is_ready))
    ct = get_ready_connection (t);
  if (NULL == ct)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
         GCT_2s (t));
    t->next_kx_attempt = GNUNET_TIME_absolute_get ();
    t->kx_auth_requested = GNUNET_YES;   /* queue KX_AUTH independent of estate */
    return;
  }
  t->kx_auth_requested = GNUNET_NO; /* clear flag */
  cc = ct->cc;
  env = GNUNET_MQ_msg (msg,
                       GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
  flags = GNUNET_CADET_KX_FLAG_NONE;
  if (GNUNET_YES == force_reply)
    flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
  msg->kx.flags = htonl (flags);
  msg->kx.cid = *GCC_get_id (cc);
  GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
                                      &msg->kx.ephemeral_key);
  GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
                                      &msg->kx.ratchet_key);
#if DEBUG_KX
  msg->kx.ephemeral_key_XXX = ax->kx_0;
  msg->kx.private_key_XXX = *my_private_key;
  msg->r_ephemeral_key_XXX = ax->last_ephemeral;
#endif
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Sending KX_AUTH message to %s with ephemeral %s on CID %s\n",
       GCT_2s (t),
       GNUNET_e2s (&msg->kx.ephemeral_key),
       GNUNET_sh2s (&msg->kx.cid.connection_of_tunnel));

  /* Compute authenticator (this is the main difference to #send_kx()) */
  GNUNET_CRYPTO_hash (&ax->RK,
                      sizeof(ax->RK),
                      &msg->auth);
  /* Compute when to be triggered again; actual job will
     be scheduled via #connection_ready_cb() */
  t->kx_retry_delay
    = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
  t->next_kx_attempt
    = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);

  /* Send via cc, mark it as unready */
  mark_connection_unready (ct);

  /* Update state machine, unless we are already OK */
  if (CADET_TUNNEL_KEY_OK != t->estate)
    GCT_change_estate (t,
                       CADET_TUNNEL_KEY_AX_AUTH_SENT);
  GCC_transmit (cc,
                env);
  GNUNET_STATISTICS_update (stats,
                            "# KX_AUTH transmitted",
                            1,
                            GNUNET_NO);
}


/**
 * Cleanup state used by @a ax.
 *
 * @param ax state to free, but not memory of @a ax itself
 */
static void
cleanup_ax (struct CadetTunnelAxolotl *ax)
{
  while (NULL != ax->skipped_head)
    delete_skipped_key (ax,
                        ax->skipped_head);
  GNUNET_assert (0 == ax->skipped);
  GNUNET_CRYPTO_ecdhe_key_clear (&ax->kx_0);
  GNUNET_CRYPTO_ecdhe_key_clear (&ax->DHRs);
}


/**
 * Update our Axolotl key state based on the KX data we received.
 * Computes the new chain keys, and root keys, etc, and also checks
 * whether this is a replay of the current chain.
 *
 * @param[in|out] axolotl chain key state to recompute
 * @param pid peer identity of the other peer
 * @param ephemeral_key ephemeral public key of the other peer
 * @param ratchet_key senders next ephemeral public key
 * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
 *       root key is already in @a ax and thus the KX is useless;
 *       #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
 */
static int
update_ax_by_kx (struct CadetTunnelAxolotl *ax,
                 const struct GNUNET_PeerIdentity *pid,
                 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
                 const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
{
  struct GNUNET_HashCode key_material[3];
  struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
  const char salt[] = "CADET Axolotl salt";
  int am_I_alice;

  if (GNUNET_SYSERR == (am_I_alice = GCT_alice_or_betty (pid)))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (0 == GNUNET_memcmp (&ax->DHRr,
                          ratchet_key))
  {
    GNUNET_STATISTICS_update (stats,
                              "# Ratchet key already known",
                              1,
                              GNUNET_NO);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Ratchet key already known. Ignoring KX.\n");
    return GNUNET_NO;
  }

  ax->DHRr = *ratchet_key;
  ax->last_ephemeral = *ephemeral_key;
  /* ECDH A B0 */
  if (GNUNET_YES == am_I_alice)
  {
    GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* a */
                              ephemeral_key,       /* B0 */
                              &key_material[0]);
  }
  else
  {
    GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0,            /* b0 */
                              &pid->public_key,     /* A */
                              &key_material[0]);
  }
  /* ECDH A0 B */
  if (GNUNET_YES == am_I_alice)
  {
    GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0,            /* a0 */
                              &pid->public_key,     /* B */
                              &key_material[1]);
  }
  else
  {
    GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* b  */
                              ephemeral_key,       /* A0 */
                              &key_material[1]);
  }

  /* ECDH A0 B0 */
  GNUNET_CRYPTO_ecc_ecdh (&ax->kx_0,              /* a0 or b0 */
                          ephemeral_key,         /* B0 or A0 */
                          &key_material[2]);
  /* KDF */
  GNUNET_CRYPTO_kdf (keys, sizeof(keys),
                     salt, sizeof(salt),
                     &key_material, sizeof(key_material),
                     NULL);

  if (0 == memcmp (&ax->RK,
                   &keys[0],
                   sizeof(ax->RK)))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Root key already known. Ignoring KX.\n");
    GNUNET_STATISTICS_update (stats,
                              "# Root key already known",
                              1,
                              GNUNET_NO);
    return GNUNET_NO;
  }

  ax->RK = keys[0];
  if (GNUNET_YES == am_I_alice)
  {
    ax->HKr = keys[1];
    ax->NHKs = keys[2];
    ax->NHKr = keys[3];
    ax->CKr = keys[4];
    ax->ratchet_flag = GNUNET_YES;
  }
  else
  {
    ax->HKs = keys[1];
    ax->NHKr = keys[2];
    ax->NHKs = keys[3];
    ax->CKs = keys[4];
    ax->ratchet_flag = GNUNET_NO;
    ax->ratchet_expiration
      = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
                                  ratchet_time);
  }
  return GNUNET_OK;
}


/**
 * Try to redo the KX or KX_AUTH handshake, if we can.
 *
 * @param cls the `struct CadetTunnel` to do KX for.
 */
static void
retry_kx (void *cls)
{
  struct CadetTunnel *t = cls;
  struct CadetTunnelAxolotl *ax;

  t->kx_task = NULL;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Trying to make KX progress on %s in state %s\n",
       GCT_2s (t),
       estate2s (t->estate));
  switch (t->estate)
  {
  case CADET_TUNNEL_KEY_UNINITIALIZED:   /* first attempt */
  case CADET_TUNNEL_KEY_AX_SENT:         /* trying again */
    send_kx (t,
             NULL,
             &t->ax);
    break;

  case CADET_TUNNEL_KEY_AX_RECV:
  case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
    /* We are responding, so only require reply
       if WE have a channel waiting. */
    if (NULL != t->unverified_ax)
    {
      /* Send AX_AUTH so we might get this one verified */
      ax = t->unverified_ax;
    }
    else
    {
      /* How can this be? */
      GNUNET_break (0);
      ax = &t->ax;
    }
    send_kx_auth (t,
                  NULL,
                  ax,
                  (0 == GCT_count_channels (t))
                  ? GNUNET_NO
                  : GNUNET_YES);
    break;

  case CADET_TUNNEL_KEY_AX_AUTH_SENT:
    /* We are responding, so only require reply
       if WE have a channel waiting. */
    if (NULL != t->unverified_ax)
    {
      /* Send AX_AUTH so we might get this one verified */
      ax = t->unverified_ax;
    }
    else
    {
      /* How can this be? */
      GNUNET_break (0);
      ax = &t->ax;
    }
    send_kx_auth (t,
                  NULL,
                  ax,
                  (0 == GCT_count_channels (t))
                  ? GNUNET_NO
                  : GNUNET_YES);
    break;

  case CADET_TUNNEL_KEY_OK:
    /* Must have been the *other* peer asking us to
       respond with a KX_AUTH. */
    if (NULL != t->unverified_ax)
    {
      /* Sending AX_AUTH in response to AX so we might get this one verified */
      ax = t->unverified_ax;
    }
    else
    {
      /* Sending AX_AUTH in response to AX_AUTH */
      ax = &t->ax;
    }
    send_kx_auth (t,
                  NULL,
                  ax,
                  GNUNET_NO);
    break;
  }
}


/**
 * Handle KX message that lacks authentication (and which will thus
 * only be considered authenticated after we respond with our own
 * KX_AUTH and finally successfully decrypt payload).
 *
 * @param ct connection/tunnel combo that received encrypted message
 * @param msg the key exchange message
 */
void
GCT_handle_kx (struct CadetTConnection *ct,
               const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
{
  struct CadetTunnel *t = ct->t;
  int ret;

  GNUNET_STATISTICS_update (stats,
                            "# KX received",
                            1,
                            GNUNET_NO);
  if (GNUNET_YES ==
      GCT_alice_or_betty (GCP_get_id (t->destination)))
  {
    /* Betty/Bob is not allowed to send KX! */
    GNUNET_break_op (0);
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Received KX message from %s with ephemeral %s from %s on connection %s\n",
       GCT_2s (t),
       GNUNET_e2s (&msg->ephemeral_key),
       GNUNET_i2s (GCP_get_id (t->destination)),
       GCC_2s (ct->cc));
#if 1
  if ((0 ==
       memcmp (&t->ax.DHRr,
               &msg->ratchet_key,
               sizeof(msg->ratchet_key))) &&
      (0 ==
       memcmp (&t->ax.last_ephemeral,
               &msg->ephemeral_key,
               sizeof(msg->ephemeral_key))))

  {
    GNUNET_STATISTICS_update (stats,
                              "# Duplicate KX received",
                              1,
                              GNUNET_NO);
    send_kx_auth (t,
                  ct,
                  &t->ax,
                  GNUNET_NO);
    return;
  }
#endif
  /* We only keep ONE unverified KX around, so if there is an existing one,
     clean it up. */
  if (NULL != t->unverified_ax)
  {
    if ((0 ==
         memcmp (&t->unverified_ax->DHRr,
                 &msg->ratchet_key,
                 sizeof(msg->ratchet_key))) &&
        (0 ==
         memcmp (&t->unverified_ax->last_ephemeral,
                 &msg->ephemeral_key,
                 sizeof(msg->ephemeral_key))))
    {
      GNUNET_STATISTICS_update (stats,
                                "# Duplicate unverified KX received",
                                1,
                                GNUNET_NO);
#if 1
      send_kx_auth (t,
                    ct,
                    t->unverified_ax,
                    GNUNET_NO);
      return;
#endif
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Dropping old unverified KX state.\n");
    GNUNET_STATISTICS_update (stats,
                              "# Unverified KX dropped for fresh KX",
                              1,
                              GNUNET_NO);
    GNUNET_break (NULL == t->unverified_ax->skipped_head);
    memset (t->unverified_ax,
            0,
            sizeof(struct CadetTunnelAxolotl));
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Creating fresh unverified KX for %s\n",
         GCT_2s (t));
    GNUNET_STATISTICS_update (stats,
                              "# Fresh KX setup",
                              1,
                              GNUNET_NO);
    t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
  }
  /* Set as the 'current' RK/DHRr the one we are currently using,
     so that the duplicate-detection logic of
   #update_ax_by_kx can work. */
  t->unverified_ax->RK = t->ax.RK;
  t->unverified_ax->DHRr = t->ax.DHRr;
  t->unverified_ax->DHRs = t->ax.DHRs;
  t->unverified_ax->kx_0 = t->ax.kx_0;
  t->unverified_attempts = 0;

  /* Update 'ax' by the new key material */
  ret = update_ax_by_kx (t->unverified_ax,
                         GCP_get_id (t->destination),
                         &msg->ephemeral_key,
                         &msg->ratchet_key);
  GNUNET_break (GNUNET_SYSERR != ret);
  if (GNUNET_OK != ret)
  {
    GNUNET_STATISTICS_update (stats,
                              "# Useless KX",
                              1,
                              GNUNET_NO);
    return;   /* duplicate KX, nothing to do */
  }
  /* move ahead in our state machine */
  if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
    GCT_change_estate (t,
                       CADET_TUNNEL_KEY_AX_RECV);
  else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
    GCT_change_estate (t,
                       CADET_TUNNEL_KEY_AX_SENT_AND_RECV);

  /* KX is still not done, try again our end. */
  if (CADET_TUNNEL_KEY_OK != t->estate)
  {
    if (NULL != t->kx_task)
      GNUNET_SCHEDULER_cancel (t->kx_task);
    t->kx_task
      = GNUNET_SCHEDULER_add_now (&retry_kx,
                                  t);
  }
}


#if DEBUG_KX
static void
check_ee (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1,
          const struct GNUNET_CRYPTO_EcdhePrivateKey *e2)
{
  struct GNUNET_CRYPTO_EcdhePublicKey p1;
  struct GNUNET_CRYPTO_EcdhePublicKey p2;
  struct GNUNET_HashCode hc1;
  struct GNUNET_HashCode hc2;

  GNUNET_CRYPTO_ecdhe_key_get_public (e1,
                                      &p1);
  GNUNET_CRYPTO_ecdhe_key_get_public (e2,
                                      &p2);
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CRYPTO_ecc_ecdh (e1,
                                         &p2,
                                         &hc1));
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CRYPTO_ecc_ecdh (e2,
                                         &p1,
                                         &hc2));
  GNUNET_break (0 == GNUNET_memcmp (&hc1,
                                    &hc2));
}


static void
check_ed (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1,
          const struct GNUNET_CRYPTO_EddsaPrivateKey *e2)
{
  struct GNUNET_CRYPTO_EcdhePublicKey p1;
  struct GNUNET_CRYPTO_EddsaPublicKey p2;
  struct GNUNET_HashCode hc1;
  struct GNUNET_HashCode hc2;

  GNUNET_CRYPTO_ecdhe_key_get_public (e1,
                                      &p1);
  GNUNET_CRYPTO_eddsa_key_get_public (e2,
                                      &p2);
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CRYPTO_ecdh_eddsa (e1,
                                           &p2,
                                           &hc1));
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CRYPTO_eddsa_ecdh (e2,
                                           &p1,
                                           &hc2));
  GNUNET_break (0 == GNUNET_memcmp (&hc1,
                                    &hc2));
}


static void
test_crypto_bug (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1,
                 const struct GNUNET_CRYPTO_EcdhePrivateKey *e2,
                 const struct GNUNET_CRYPTO_EddsaPrivateKey *d1,
                 const struct GNUNET_CRYPTO_EddsaPrivateKey *d2)
{
  check_ee (e1, e2);
  check_ed (e1, d2);
  check_ed (e2, d1);
}


#endif


/**
 * Handle KX_AUTH message.
 *
 * @param ct connection/tunnel combo that received encrypted message
 * @param msg the key exchange message
 */
void
GCT_handle_kx_auth (struct CadetTConnection *ct,
                    const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
{
  struct CadetTunnel *t = ct->t;
  struct CadetTunnelAxolotl ax_tmp;
  struct GNUNET_HashCode kx_auth;
  int ret;

  GNUNET_STATISTICS_update (stats,
                            "# KX_AUTH received",
                            1,
                            GNUNET_NO);
  if ((CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
      (CADET_TUNNEL_KEY_AX_RECV == t->estate))
  {
    /* Confusing, we got a KX_AUTH before we even send our own
       KX. This should not happen. We'll send our own KX ASAP anyway,
       so let's ignore this here. */
    GNUNET_break_op (0);
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Handling KX_AUTH message from %s with ephemeral %s\n",
       GCT_2s (t),
       GNUNET_e2s (&msg->kx.ephemeral_key));
  /* We do everything in ax_tmp until we've checked the authentication
     so we don't clobber anything we care about by accident. */
  ax_tmp = t->ax;

  /* Update 'ax' by the new key material */
  ret = update_ax_by_kx (&ax_tmp,
                         GCP_get_id (t->destination),
                         &msg->kx.ephemeral_key,
                         &msg->kx.ratchet_key);
  if (GNUNET_OK != ret)
  {
    if (GNUNET_NO == ret)
      GNUNET_STATISTICS_update (stats,
                                "# redundant KX_AUTH received",
                                1,
                                GNUNET_NO);
    else
      GNUNET_break (0);  /* connect to self!? */
    return;
  }
  GNUNET_CRYPTO_hash (&ax_tmp.RK,
                      sizeof(ax_tmp.RK),
                      &kx_auth);
  if (0 != GNUNET_memcmp (&kx_auth,
                          &msg->auth))
  {
    /* This KX_AUTH is not using the latest KX/KX_AUTH data
       we transmitted to the sender, refuse it, try KX again. */
    GNUNET_STATISTICS_update (stats,
                              "# KX_AUTH not using our last KX received (auth failure)",
                              1,
                              GNUNET_NO);
    LOG (GNUNET_ERROR_TYPE_WARNING,
         "KX AUTH mismatch!\n");
#if DEBUG_KX
    {
      struct GNUNET_CRYPTO_EcdhePublicKey ephemeral_key;

      GNUNET_CRYPTO_ecdhe_key_get_public (&ax_tmp.kx_0,
                                          &ephemeral_key);
      if (0 != GNUNET_memcmp (&ephemeral_key,
                              &msg->r_ephemeral_key_XXX))
      {
        LOG (GNUNET_ERROR_TYPE_WARNING,
             "My ephemeral is %s!\n",
             GNUNET_e2s (&ephemeral_key));
        LOG (GNUNET_ERROR_TYPE_WARNING,
             "Response is for ephemeral %s!\n",
             GNUNET_e2s (&msg->r_ephemeral_key_XXX));
      }
      else
      {
        test_crypto_bug (&ax_tmp.kx_0,
                         &msg->kx.ephemeral_key_XXX,
                         my_private_key,
                         &msg->kx.private_key_XXX);
      }
    }
#endif
    if (NULL == t->kx_task)
      t->kx_task
        = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
                                   &retry_kx,
                                   t);
    return;
  }
  /* Yep, we're good. */
  t->ax = ax_tmp;
  if (NULL != t->unverified_ax)
  {
    /* We got some "stale" KX before, drop that. */
    cleanup_ax (t->unverified_ax);
    GNUNET_free (t->unverified_ax);
    t->unverified_ax = NULL;
  }

  /* move ahead in our state machine */
  switch (t->estate)
  {
  case CADET_TUNNEL_KEY_UNINITIALIZED:
  case CADET_TUNNEL_KEY_AX_RECV:
    /* Checked above, this is impossible. */
    GNUNET_assert (0);
    break;

  case CADET_TUNNEL_KEY_AX_SENT:      /* This is the normal case */
  case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:   /* both peers started KX */
  case CADET_TUNNEL_KEY_AX_AUTH_SENT:   /* both peers now did KX_AUTH */
    GCT_change_estate (t,
                       CADET_TUNNEL_KEY_OK);
    break;

  case CADET_TUNNEL_KEY_OK:
    /* Did not expect another KX_AUTH, but so what, still acceptable.
       Nothing to do here. */
    break;
  }
  if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->kx.flags)))
  {
    send_kx_auth (t,
                  NULL,
                  &t->ax,
                  GNUNET_NO);
  }
}


/* ************************************** end core crypto ***************************** */


/**
 * Compute the next free channel tunnel number for this tunnel.
 *
 * @param t the tunnel
 * @return unused number that can uniquely identify a channel in the tunnel
 */
static struct GNUNET_CADET_ChannelTunnelNumber
get_next_free_ctn (struct CadetTunnel *t)
{
#define HIGH_BIT 0x8000000
  struct GNUNET_CADET_ChannelTunnelNumber ret;
  uint32_t ctn;
  int cmp;
  uint32_t highbit;

  cmp = GNUNET_memcmp (&my_full_id,
                       GCP_get_id (GCT_get_destination (t)));
  if (0 < cmp)
    highbit = HIGH_BIT;
  else if (0 > cmp)
    highbit = 0;
  else
    GNUNET_assert (0); // loopback must never go here!
  ctn = ntohl (t->next_ctn.cn);
  while (NULL !=
         GNUNET_CONTAINER_multihashmap32_get (t->channels,
                                              ctn | highbit))
  {
    ctn = ((ctn + 1) & (~HIGH_BIT));
  }
  t->next_ctn.cn = htonl ((ctn + 1) & (~HIGH_BIT));
  ret.cn = htonl (ctn | highbit);
  return ret;
}


/**
 * Add a channel to a tunnel, and notify channel that we are ready
 * for transmission if we are already up.  Otherwise that notification
 * will be done later in #notify_tunnel_up_cb().
 *
 * @param t Tunnel.
 * @param ch Channel
 * @return unique number identifying @a ch within @a t
 */
struct GNUNET_CADET_ChannelTunnelNumber
GCT_add_channel (struct CadetTunnel *t,
                 struct CadetChannel *ch)
{
  struct GNUNET_CADET_ChannelTunnelNumber ctn;

  ctn = get_next_free_ctn (t);
  if (NULL != t->destroy_task)
  {
    GNUNET_SCHEDULER_cancel (t->destroy_task);
    t->destroy_task = NULL;
  }
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap32_put (t->channels,
                                                      ntohl (ctn.cn),
                                                      ch,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Adding %s to %s with state %d\n",
       GCCH_2s (ch),
       GCT_2s (t),
       t->estate);
  switch (t->estate)
  {
  case CADET_TUNNEL_KEY_UNINITIALIZED:
    /* waiting for connection to start KX */
    break;

  case CADET_TUNNEL_KEY_AX_RECV:
  case CADET_TUNNEL_KEY_AX_SENT:
  case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
    /* we're currently waiting for KX to complete */
    break;

  case CADET_TUNNEL_KEY_AX_AUTH_SENT:
    /* waiting for OTHER peer to send us data,
       we might need to prompt more aggressively! */
    if (NULL == t->kx_task)
      t->kx_task
        = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
                                   &retry_kx,
                                   t);
    break;

  case CADET_TUNNEL_KEY_OK:
    /* We are ready. Tell the new channel that we are up. */
    GCCH_tunnel_up (ch);
    break;
  }
  return ctn;
}


/**
 * We lost a connection, remove it from our list and clean up
 * the connection object itself.
 *
 * @param ct binding of connection to tunnel of the connection that was lost.
 */
void
GCT_connection_lost (struct CadetTConnection *ct)
{
  struct CadetTunnel *t = ct->t;

  if (GNUNET_YES == ct->is_ready)
  {
    GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
                                 t->connection_ready_tail,
                                 ct);
    t->num_ready_connections--;
  }
  else
  {
    GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
                                 t->connection_busy_tail,
                                 ct);
    t->num_busy_connections--;
  }
  GNUNET_free (ct);
}


/**
 * Clean up connection @a ct of a tunnel.
 *
 * @param cls the `struct CadetTunnel`
 * @param ct connection to clean up
 */
static void
destroy_t_connection (void *cls,
                      struct CadetTConnection *ct)
{
  struct CadetTunnel *t = cls;
  struct CadetConnection *cc = ct->cc;

  GNUNET_assert (ct->t == t);
  GCT_connection_lost (ct);
  GCC_destroy_without_tunnel (cc);
}


/**
 * This tunnel is no longer used, destroy it.
 *
 * @param cls the idle tunnel
 */
static void
destroy_tunnel (void *cls)
{
  struct CadetTunnel *t = cls;
  struct CadetTunnelQueueEntry *tq;

  t->destroy_task = NULL;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Destroying idle %s\n",
       GCT_2s (t));
  GNUNET_assert (0 == GCT_count_channels (t));
  GCT_iterate_connections (t,
                           &destroy_t_connection,
                           t);
  GNUNET_assert (NULL == t->connection_ready_head);
  GNUNET_assert (NULL == t->connection_busy_head);
  while (NULL != (tq = t->tq_head))
  {
    if (NULL != tq->cont)
      tq->cont (tq->cont_cls,
                NULL);
    GCT_send_cancel (tq);
  }
  GCP_drop_tunnel (t->destination,
                   t);
  GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
  if (NULL != t->maintain_connections_task)
  {
    GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
    t->maintain_connections_task = NULL;
  }
  if (NULL != t->send_task)
  {
    GNUNET_SCHEDULER_cancel (t->send_task);
    t->send_task = NULL;
  }
  if (NULL != t->kx_task)
  {
    GNUNET_SCHEDULER_cancel (t->kx_task);
    t->kx_task = NULL;
  }
  GNUNET_MST_destroy (t->mst);
  GNUNET_MQ_destroy (t->mq);
  if (NULL != t->unverified_ax)
  {
    cleanup_ax (t->unverified_ax);
    GNUNET_free (t->unverified_ax);
  }
  cleanup_ax (&t->ax);
  GNUNET_assert (NULL == t->destroy_task);
  GNUNET_free (t);
}


/**
 * Remove a channel from a tunnel.
 *
 * @param t Tunnel.
 * @param ch Channel
 * @param ctn unique number identifying @a ch within @a t
 */
void
GCT_remove_channel (struct CadetTunnel *t,
                    struct CadetChannel *ch,
                    struct GNUNET_CADET_ChannelTunnelNumber ctn)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Removing %s from %s\n",
       GCCH_2s (ch),
       GCT_2s (t));
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
                                                         ntohl (ctn.cn),
                                                         ch));
  if ((0 ==
       GCT_count_channels (t)) &&
      (NULL == t->destroy_task))
  {
    t->destroy_task
      = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
                                      &destroy_tunnel,
                                      t);
  }
}


/**
 * Destroy remaining channels during shutdown.
 *
 * @param cls the `struct CadetTunnel` of the channel
 * @param key key of the channel
 * @param value the `struct CadetChannel`
 * @return #GNUNET_OK (continue to iterate)
 */
static int
destroy_remaining_channels (void *cls,
                            uint32_t key,
                            void *value)
{
  struct CadetChannel *ch = value;

  GCCH_handle_remote_destroy (ch,
                              NULL);
  return GNUNET_OK;
}


/**
 * Destroys the tunnel @a t now, without delay. Used during shutdown.
 *
 * @param t tunnel to destroy
 */
void
GCT_destroy_tunnel_now (struct CadetTunnel *t)
{
  GNUNET_assert (GNUNET_YES == shutting_down);
  GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
                                           &destroy_remaining_channels,
                                           t);
  GNUNET_assert (0 ==
                 GCT_count_channels (t));
  if (NULL != t->destroy_task)
  {
    GNUNET_SCHEDULER_cancel (t->destroy_task);
    t->destroy_task = NULL;
  }
  destroy_tunnel (t);
}


/**
 * Send normal payload from queue in @a t via connection @a ct.
 * Does nothing if our payload queue is empty.
 *
 * @param t tunnel to send data from
 * @param ct connection to use for transmission (is ready)
 */
static void
try_send_normal_payload (struct CadetTunnel *t,
                         struct CadetTConnection *ct)
{
  struct CadetTunnelQueueEntry *tq;

  GNUNET_assert (GNUNET_YES == ct->is_ready);
  tq = t->tq_head;
  if (NULL == tq)
  {
    /* no messages pending right now */
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Not sending payload of %s on ready %s (nothing pending)\n",
         GCT_2s (t),
         GCC_2s (ct->cc));
    return;
  }
  /* ready to send message 'tq' on tunnel 'ct' */
  GNUNET_assert (t == tq->t);
  GNUNET_CONTAINER_DLL_remove (t->tq_head,
                               t->tq_tail,
                               tq);
  if (NULL != tq->cid)
    *tq->cid = *GCC_get_id (ct->cc);
  mark_connection_unready (ct);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Sending payload of %s on %s\n",
       GCT_2s (t),
       GCC_2s (ct->cc));
  GCC_transmit (ct->cc,
                tq->env);
  if (NULL != tq->cont)
    tq->cont (tq->cont_cls,
              GCC_get_id (ct->cc));
  GNUNET_free (tq);
}


/**
 * A connection is @a is_ready for transmission.  Looks at our message
 * queue and if there is a message, sends it out via the connection.
 *
 * @param cls the `struct CadetTConnection` that is @a is_ready
 * @param is_ready #GNUNET_YES if connection are now ready,
 *                 #GNUNET_NO if connection are no longer ready
 */
static void
connection_ready_cb (void *cls,
                     int is_ready)
{
  struct CadetTConnection *ct = cls;
  struct CadetTunnel *t = ct->t;

  if (GNUNET_NO == is_ready)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s no longer ready for %s\n",
         GCC_2s (ct->cc),
         GCT_2s (t));
    mark_connection_unready (ct);
    return;
  }
  GNUNET_assert (GNUNET_NO == ct->is_ready);
  GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
                               t->connection_busy_tail,
                               ct);
  GNUNET_assert (0 < t->num_busy_connections);
  t->num_busy_connections--;
  ct->is_ready = GNUNET_YES;
  GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head,
                                    t->connection_ready_tail,
                                    ct);
  t->num_ready_connections++;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s now ready for %s in state %s\n",
       GCC_2s (ct->cc),
       GCT_2s (t),
       estate2s (t->estate));
  switch (t->estate)
  {
  case CADET_TUNNEL_KEY_UNINITIALIZED:
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Do not begin KX for %s if WE have no channels waiting. Retrying after %llu\n",
         GCT_2s (t),
         (unsigned long long) GNUNET_TIME_absolute_get_remaining (
           t->next_kx_attempt).rel_value_us);
    /* Do not begin KX if WE have no channels waiting! */
    if (0 != GNUNET_TIME_absolute_get_remaining (
          t->next_kx_attempt).rel_value_us)
      return;   /* wait for timeout before retrying */
    /* We are uninitialized, just transmit immediately,
       without undue delay. */

    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Why for %s \n",
         GCT_2s (t));

    if (NULL != t->kx_task)
    {
      GNUNET_SCHEDULER_cancel (t->kx_task);
      t->kx_task = NULL;
    }
    send_kx (t,
             ct,
             &t->ax);
    if ((0 ==
         GCT_count_channels (t)) &&
        (NULL == t->destroy_task))
    {
      t->destroy_task
        = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
                                        &destroy_tunnel,
                                        t);
    }
    break;

  case CADET_TUNNEL_KEY_AX_RECV:
  case CADET_TUNNEL_KEY_AX_SENT:
  case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
  case CADET_TUNNEL_KEY_AX_AUTH_SENT:
    /* we're currently waiting for KX to complete, schedule job */
    if (NULL == t->kx_task)
      t->kx_task
        = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
                                   &retry_kx,
                                   t);
    break;

  case CADET_TUNNEL_KEY_OK:
    if (GNUNET_YES == t->kx_auth_requested)
    {
      if (0 != GNUNET_TIME_absolute_get_remaining (
            t->next_kx_attempt).rel_value_us)
        return;     /* wait for timeout */
      if (NULL != t->kx_task)
      {
        GNUNET_SCHEDULER_cancel (t->kx_task);
        t->kx_task = NULL;
      }
      send_kx_auth (t,
                    ct,
                    &t->ax,
                    GNUNET_NO);
      return;
    }
    try_send_normal_payload (t,
                             ct);
    break;
  }
}


/**
 * Called when either we have a new connection, or a new message in the
 * queue, or some existing connection has transmission capacity.  Looks
 * at our message queue and if there is a message, picks a connection
 * to send it on.
 *
 * @param cls the `struct CadetTunnel` to process messages on
 */
static void
trigger_transmissions (void *cls)
{
  struct CadetTunnel *t = cls;
  struct CadetTConnection *ct;

  t->send_task = NULL;
  if (NULL == t->tq_head)
    return; /* no messages pending right now */
  ct = get_ready_connection (t);
  if (NULL == ct)
    return; /* no connections ready */
  try_send_normal_payload (t,
                           ct);
}


/**
 * Closure for #evaluate_connection. Used to assemble summary information
 * about the existing connections so we can evaluate a new path.
 */
struct EvaluationSummary
{
  /**
   * Minimum length of any of our connections, `UINT_MAX` if we have none.
   */
  unsigned int min_length;

  /**
   * Maximum length of any of our connections, 0 if we have none.
   */
  unsigned int max_length;

  /**
   * Minimum desirability of any of our connections, UINT64_MAX if we have none.
   */
  GNUNET_CONTAINER_HeapCostType min_desire;

  /**
   * Maximum desirability of any of our connections, 0 if we have none.
   */
  GNUNET_CONTAINER_HeapCostType max_desire;

  /**
   * Path we are comparing against for #evaluate_connection, can be NULL.
   */
  struct CadetPeerPath *path;

  /**
   * Connection deemed the "worst" so far encountered by #evaluate_connection,
   * NULL if we did not yet encounter any connections.
   */
  struct CadetTConnection *worst;

  /**
   * Numeric score of @e worst, only set if @e worst is non-NULL.
   */
  double worst_score;

  /**
   * Set to #GNUNET_YES if we have a connection over @e path already.
   */
  int duplicate;
};


/**
 * Evaluate a connection, updating our summary information in @a cls about
 * what kinds of connections we have.
 *
 * @param cls the `struct EvaluationSummary *` to update
 * @param ct a connection to include in the summary
 */
static void
evaluate_connection (void *cls,
                     struct CadetTConnection *ct)
{
  struct EvaluationSummary *es = cls;
  struct CadetConnection *cc = ct->cc;
  unsigned int ct_length;
  struct CadetPeerPath *ps;
  const struct CadetConnectionMetrics *metrics;
  GNUNET_CONTAINER_HeapCostType ct_desirability;
  struct GNUNET_TIME_Relative uptime;
  struct GNUNET_TIME_Relative last_use;
  double score;
  double success_rate;

  ps = GCC_get_path (cc,
                     &ct_length);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Evaluating path %s of existing %s\n",
       GCPP_2s (ps),
       GCC_2s (cc));
  if (ps == es->path)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Ignoring duplicate path %s.\n",
         GCPP_2s (es->path));
    es->duplicate = GNUNET_YES;
    return;
  }
  if (NULL != es->path)
  {
    int duplicate = GNUNET_YES;

    for (unsigned int i = 0; i < ct_length; i++)
    {
      GNUNET_assert (GCPP_get_length (es->path) > i);
      if (GCPP_get_peer_at_offset (es->path,
                                   i) !=
          GCPP_get_peer_at_offset (ps,
                                   i))
      {
        duplicate = GNUNET_NO;
        break;
      }
    }
    if (GNUNET_YES == duplicate)
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Ignoring overlapping path %s.\n",
           GCPP_2s (es->path));
      es->duplicate = GNUNET_YES;
      return;
    }
    else
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Known path %s differs from proposed path\n",
           GCPP_2s (ps));
    }
  }

  ct_desirability = GCPP_get_desirability (ps);
  metrics = GCC_get_metrics (cc);
  uptime = GNUNET_TIME_absolute_get_duration (metrics->age);
  last_use = GNUNET_TIME_absolute_get_duration (metrics->last_use);
  /* We add 1.0 here to avoid division by zero. */
  success_rate = (metrics->num_acked_transmissions + 1.0)
                 / (metrics->num_successes + 1.0);
  score
    = ct_desirability
      + 100.0 / (1.0 + ct_length) /* longer paths = better */
      + sqrt (uptime.rel_value_us / 60000000LL) /* larger uptime = better */
      - last_use.rel_value_us / 1000L;        /* longer idle = worse */
  score *= success_rate;        /* weigh overall by success rate */

  if ((NULL == es->worst) ||
      (score < es->worst_score))
  {
    es->worst = ct;
    es->worst_score = score;
  }
  es->min_length = GNUNET_MIN (es->min_length,
                               ct_length);
  es->max_length = GNUNET_MAX (es->max_length,
                               ct_length);
  es->min_desire = GNUNET_MIN (es->min_desire,
                               ct_desirability);
  es->max_desire = GNUNET_MAX (es->max_desire,
                               ct_desirability);
}


/**
 * Consider using the path @a p for the tunnel @a t.
 * The tunnel destination is at offset @a off in path @a p.
 *
 * @param cls our tunnel
 * @param path a path to our destination
 * @param off offset of the destination on path @a path
 * @return #GNUNET_YES (should keep iterating)
 */
static int
consider_path_cb (void *cls,
                  struct CadetPeerPath *path,
                  unsigned int off)
{
  struct CadetTunnel *t = cls;
  struct EvaluationSummary es;
  struct CadetTConnection *ct;

  GNUNET_assert (off < GCPP_get_length (path));
  GNUNET_assert (GCPP_get_peer_at_offset (path,
                                          off) == t->destination);
  es.min_length = UINT_MAX;
  es.max_length = 0;
  es.max_desire = 0;
  es.min_desire = UINT64_MAX;
  es.path = path;
  es.duplicate = GNUNET_NO;
  es.worst = NULL;

  /* Compute evaluation summary over existing connections. */
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Evaluating proposed path %s for target %s\n",
       GCPP_2s (path),
       GCT_2s (t));
  /* FIXME: suspect this does not ACTUALLY iterate
     over all existing paths, otherwise dup detection
     should work!!! */
  GCT_iterate_connections (t,
                           &evaluate_connection,
                           &es);
  if (GNUNET_YES == es.duplicate)
    return GNUNET_YES;

  /* FIXME: not sure we should really just count
     'num_connections' here, as they may all have
     consistently failed to connect. */

  /* We iterate by increasing path length; if we have enough paths and
     this one is more than twice as long than what we are currently
     using, then ignore all of these super-long ones! */
  if ((GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) &&
      (es.min_length * 2 < off) &&
      (es.max_length < off))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Ignoring paths of length %u, they are way too long.\n",
         es.min_length * 2);
    return GNUNET_NO;
  }
  /* If we have enough paths and this one looks no better, ignore it. */
  if ((GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
      (es.min_length < GCPP_get_length (path)) &&
      (es.min_desire > GCPP_get_desirability (path)) &&
      (es.max_length < off))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Ignoring path (%u/%llu) to %s, got something better already.\n",
         GCPP_get_length (path),
         (unsigned long long) GCPP_get_desirability (path),
         GCP_2s (t->destination));
    return GNUNET_YES;
  }

  /* Path is interesting (better by some metric, or we don't have
     enough paths yet). */
  ct = GNUNET_new (struct CadetTConnection);
  ct->created = GNUNET_TIME_absolute_get ();
  ct->t = t;
  ct->cc = GCC_create (t->destination,
                       path,
                       off,
                       ct,
                       &connection_ready_cb,
                       ct);

  /* FIXME: schedule job to kill connection (and path?)  if it takes
     too long to get ready! (And track performance data on how long
     other connections took with the tunnel!)
     => Note: to be done within 'connection'-logic! */
  GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
                               t->connection_busy_tail,
                               ct);
  t->num_busy_connections++;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Found interesting path %s for %s, created %s\n",
       GCPP_2s (path),
       GCT_2s (t),
       GCC_2s (ct->cc));
  return GNUNET_YES;
}


/**
 * Function called to maintain the connections underlying our tunnel.
 * Tries to maintain (incl. tear down) connections for the tunnel, and
 * if there is a significant change, may trigger transmissions.
 *
 * Basically, needs to check if there are connections that perform
 * badly, and if so eventually kill them and trigger a replacement.
 * The strategy is to open one more connection than
 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
 * least-performing one, and then inquire for new ones.
 *
 * @param cls the `struct CadetTunnel`
 */
static void
maintain_connections_cb (void *cls)
{
  struct CadetTunnel *t = cls;
  struct GNUNET_TIME_Relative delay;
  struct EvaluationSummary es;

  t->maintain_connections_task = NULL;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Performing connection maintenance for %s.\n",
       GCT_2s (t));

  es.min_length = UINT_MAX;
  es.max_length = 0;
  es.max_desire = 0;
  es.min_desire = UINT64_MAX;
  es.path = NULL;
  es.worst = NULL;
  es.duplicate = GNUNET_NO;
  GCT_iterate_connections (t,
                           &evaluate_connection,
                           &es);
  if ((NULL != es.worst) &&
      (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL))
  {
    /* Clear out worst-performing connection 'es.worst'. */
    destroy_t_connection (t,
                          es.worst);
  }

  /* Consider additional paths */
  (void) GCP_iterate_paths (t->destination,
                            &consider_path_cb,
                            t);

  /* FIXME: calculate when to try again based on how well we are doing;
     in particular, if we have to few connections, we might be able
     to do without this (as PATHS should tell us whenever a new path
     is available instantly; however, need to make sure this job is
     restarted after that happens).
     Furthermore, if the paths we do know are in a reasonably narrow
     quality band and are plentyful, we might also consider us stabilized
     and then reduce the frequency accordingly.  */delay = GNUNET_TIME_UNIT_MINUTES;
  t->maintain_connections_task
    = GNUNET_SCHEDULER_add_delayed (delay,
                                    &maintain_connections_cb,
                                    t);
}


/**
 * Consider using the path @a p for the tunnel @a t.
 * The tunnel destination is at offset @a off in path @a p.
 *
 * @param cls our tunnel
 * @param path a path to our destination
 * @param off offset of the destination on path @a path
 */
void
GCT_consider_path (struct CadetTunnel *t,
                   struct CadetPeerPath *p,
                   unsigned int off)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Considering %s for %s (offset %u)\n",
       GCPP_2s (p),
       GCT_2s (t),
       off);
  (void) consider_path_cb (t,
                           p,
                           off);
}


/**
 * We got a keepalive. Track in statistics.
 *
 * @param cls the `struct CadetTunnel` for which we decrypted the message
 * @param msg  the message we received on the tunnel
 */
static void
handle_plaintext_keepalive (void *cls,
                            const struct GNUNET_MessageHeader *msg)
{
  struct CadetTunnel *t = cls;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Received KEEPALIVE on %s\n",
       GCT_2s (t));
  GNUNET_STATISTICS_update (stats,
                            "# keepalives received",
                            1,
                            GNUNET_NO);
}


/**
 * Check that @a msg is well-formed.
 *
 * @param cls the `struct CadetTunnel` for which we decrypted the message
 * @param msg  the message we received on the tunnel
 * @return #GNUNET_OK (any variable-size payload goes)
 */
static int
check_plaintext_data (void *cls,
                      const struct GNUNET_CADET_ChannelAppDataMessage *msg)
{
  return GNUNET_OK;
}


/**
 * We received payload data for a channel.  Locate the channel
 * and process the data, or return an error if the channel is unknown.
 *
 * @param cls the `struct CadetTunnel` for which we decrypted the message
 * @param msg the message we received on the tunnel
 */
static void
handle_plaintext_data (void *cls,
                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
{
  struct CadetTunnel *t = cls;
  struct CadetChannel *ch;

  ch = lookup_channel (t,
                       msg->ctn);
  if (NULL == ch)
  {
    /* We don't know about such a channel, might have been destroyed on our
       end in the meantime, or never existed. Send back a DESTROY. */
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Received %u bytes of application data for unknown channel %u, sending DESTROY\n",
         (unsigned int) (ntohs (msg->header.size) - sizeof(*msg)),
         ntohl (msg->ctn.cn));
    GCT_send_channel_destroy (t,
                              msg->ctn);
    return;
  }
  GCCH_handle_channel_plaintext_data (ch,
                                      GCC_get_id (t->current_ct->cc),
                                      msg);
}


/**
 * We received an acknowledgement for data we sent on a channel.
 * Locate the channel and process it, or return an error if the
 * channel is unknown.
 *
 * @param cls the `struct CadetTunnel` for which we decrypted the message
 * @param ack the message we received on the tunnel
 */
static void
handle_plaintext_data_ack (void *cls,
                           const struct GNUNET_CADET_ChannelDataAckMessage *ack)
{
  struct CadetTunnel *t = cls;
  struct CadetChannel *ch;

  ch = lookup_channel (t,
                       ack->ctn);
  if (NULL == ch)
  {
    /* We don't know about such a channel, might have been destroyed on our
       end in the meantime, or never existed. Send back a DESTROY. */
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Received DATA_ACK for unknown channel %u, sending DESTROY\n",
         ntohl (ack->ctn.cn));
    GCT_send_channel_destroy (t,
                              ack->ctn);
    return;
  }
  GCCH_handle_channel_plaintext_data_ack (ch,
                                          GCC_get_id (t->current_ct->cc),
                                          ack);
}


/**
 * We have received a request to open a channel to a port from
 * another peer.  Creates the incoming channel.
 *
 * @param cls the `struct CadetTunnel` for which we decrypted the message
 * @param copen the message we received on the tunnel
 */
static void
handle_plaintext_channel_open (void *cls,
                               const struct
                               GNUNET_CADET_ChannelOpenMessage *copen)
{
  struct CadetTunnel *t = cls;
  struct CadetChannel *ch;

  ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
                                            ntohl (copen->ctn.cn));
  if (NULL != ch)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Received duplicate channel CHANNEL_OPEN on h_port %s from %s (%s), resending ACK\n",
         GNUNET_h2s (&copen->h_port),
         GCT_2s (t),
         GCCH_2s (ch));
    GCCH_handle_duplicate_open (ch,
                                GCC_get_id (t->current_ct->cc));
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Received CHANNEL_OPEN on h_port %s from %s\n",
       GNUNET_h2s (&copen->h_port),
       GCT_2s (t));
  ch = GCCH_channel_incoming_new (t,
                                  copen->ctn,
                                  &copen->h_port,
                                  ntohl (copen->opt));
  if (NULL != t->destroy_task)
  {
    GNUNET_SCHEDULER_cancel (t->destroy_task);
    t->destroy_task = NULL;
  }
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multihashmap32_put (t->channels,
                                                      ntohl (copen->ctn.cn),
                                                      ch,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
}


/**
 * Send a DESTROY message via the tunnel.
 *
 * @param t the tunnel to transmit over
 * @param ctn ID of the channel to destroy
 */
void
GCT_send_channel_destroy (struct CadetTunnel *t,
                          struct GNUNET_CADET_ChannelTunnelNumber ctn)
{
  struct GNUNET_CADET_ChannelDestroyMessage msg;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Sending DESTORY message for channel ID %u\n",
       ntohl (ctn.cn));
  msg.header.size = htons (sizeof(msg));
  msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
  msg.reserved = htonl (0);
  msg.ctn = ctn;
  GCT_send (t,
            &msg.header,
            NULL,
            NULL,
            &ctn);
}


/**
 * We have received confirmation from the target peer that the
 * given channel could be established (the port is open).
 * Tell the client.
 *
 * @param cls the `struct CadetTunnel` for which we decrypted the message
 * @param cm the message we received on the tunnel
 */
static void
handle_plaintext_channel_open_ack (void *cls,
                                   const struct
                                   GNUNET_CADET_ChannelOpenAckMessage *cm)
{
  struct CadetTunnel *t = cls;
  struct CadetChannel *ch;

  ch = lookup_channel (t,
                       cm->ctn);
  if (NULL == ch)
  {
    /* We don't know about such a channel, might have been destroyed on our
       end in the meantime, or never existed. Send back a DESTROY. */
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
         ntohl (cm->ctn.cn));
    GCT_send_channel_destroy (t,
                              cm->ctn);
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Received channel OPEN_ACK on channel %s from %s\n",
       GCCH_2s (ch),
       GCT_2s (t));
  GCCH_handle_channel_open_ack (ch,
                                GCC_get_id (t->current_ct->cc),
                                &cm->port);
}


/**
 * We received a message saying that a channel should be destroyed.
 * Pass it on to the correct channel.
 *
 * @param cls the `struct CadetTunnel` for which we decrypted the message
 * @param cm the message we received on the tunnel
 */
static void
handle_plaintext_channel_destroy (void *cls,
                                  const struct
                                  GNUNET_CADET_ChannelDestroyMessage *cm)
{
  struct CadetTunnel *t = cls;
  struct CadetChannel *ch;

  ch = lookup_channel (t,
                       cm->ctn);
  if (NULL == ch)
  {
    /* We don't know about such a channel, might have been destroyed on our
       end in the meantime, or never existed. */
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Received channel DESTORY for unknown channel %u. Ignoring.\n",
         ntohl (cm->ctn.cn));
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Received channel DESTROY on %s from %s\n",
       GCCH_2s (ch),
       GCT_2s (t));
  GCCH_handle_remote_destroy (ch,
                              GCC_get_id (t->current_ct->cc));
}


/**
 * Handles a message we decrypted, by injecting it into
 * our message queue (which will do the dispatching).
 *
 * @param cls the `struct CadetTunnel` that got the message
 * @param msg the message
 * @return #GNUNET_OK on success (always)
 *    #GNUNET_NO to stop further processing (no error)
 *    #GNUNET_SYSERR to stop further processing with error
 */
static int
handle_decrypted (void *cls,
                  const struct GNUNET_MessageHeader *msg)
{
  struct CadetTunnel *t = cls;

  GNUNET_assert (NULL != t->current_ct);
  GNUNET_MQ_inject_message (t->mq,
                            msg);
  return GNUNET_OK;
}


/**
 * Function called if we had an error processing
 * an incoming decrypted message.
 *
 * @param cls the `struct CadetTunnel`
 * @param error error code
 */
static void
decrypted_error_cb (void *cls,
                    enum GNUNET_MQ_Error error)
{
  GNUNET_break_op (0);
}


/**
 * Create a tunnel to @a destionation.  Must only be called
 * from within #GCP_get_tunnel().
 *
 * @param destination where to create the tunnel to
 * @return new tunnel to @a destination
 */
struct CadetTunnel *
GCT_create_tunnel (struct CadetPeer *destination)
{
  struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
  struct GNUNET_MQ_MessageHandler handlers[] = {
    GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
                             GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
                             struct GNUNET_MessageHeader,
                             t),
    GNUNET_MQ_hd_var_size (plaintext_data,
                           GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
                           struct GNUNET_CADET_ChannelAppDataMessage,
                           t),
    GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
                             GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
                             struct GNUNET_CADET_ChannelDataAckMessage,
                             t),
    GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
                             GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
                             struct GNUNET_CADET_ChannelOpenMessage,
                             t),
    GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
                             GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
                             struct GNUNET_CADET_ChannelOpenAckMessage,
                             t),
    GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
                             GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
                             struct GNUNET_CADET_ChannelDestroyMessage,
                             t),
    GNUNET_MQ_handler_end ()
  };

  t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
  new_ephemeral (&t->ax);
  GNUNET_CRYPTO_ecdhe_key_create (&t->ax.kx_0);
  t->destination = destination;
  t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
  t->maintain_connections_task
    = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
                                t);
  t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
                                         NULL,
                                         NULL,
                                         NULL,
                                         handlers,
                                         &decrypted_error_cb,
                                         t);
  t->mst = GNUNET_MST_create (&handle_decrypted,
                              t);
  return t;
}


/**
 * Add a @a connection to the @a tunnel.
 *
 * @param t a tunnel
 * @param cid connection identifer to use for the connection
 * @param options options for the connection
 * @param path path to use for the connection
 * @return #GNUNET_OK on success,
 *         #GNUNET_SYSERR on failure (duplicate connection)
 */
int
GCT_add_inbound_connection (struct CadetTunnel *t,
                            const struct
                            GNUNET_CADET_ConnectionTunnelIdentifier *cid,
                            struct CadetPeerPath *path)
{
  struct CadetTConnection *ct;

  ct = GNUNET_new (struct CadetTConnection);
  ct->created = GNUNET_TIME_absolute_get ();
  ct->t = t;
  ct->cc = GCC_create_inbound (t->destination,
                               path,
                               ct,
                               cid,
                               &connection_ready_cb,
                               ct);
  if (NULL == ct->cc)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s refused inbound %s (duplicate)\n",
         GCT_2s (t),
         GCC_2s (ct->cc));
    GNUNET_free (ct);
    return GNUNET_SYSERR;
  }
  /* FIXME: schedule job to kill connection (and path?)  if it takes
     too long to get ready! (And track performance data on how long
     other connections took with the tunnel!)
     => Note: to be done within 'connection'-logic! */
  GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
                               t->connection_busy_tail,
                               ct);
  t->num_busy_connections++;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s has new %s\n",
       GCT_2s (t),
       GCC_2s (ct->cc));
  return GNUNET_OK;
}


/**
 * Handle encrypted message.
 *
 * @param ct connection/tunnel combo that received encrypted message
 * @param msg the encrypted message to decrypt
 */
void
GCT_handle_encrypted (struct CadetTConnection *ct,
                      const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
{
  struct CadetTunnel *t = ct->t;
  uint16_t size = ntohs (msg->header.size);
  char cbuf[size] GNUNET_ALIGN;
  ssize_t decrypted_size;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s received %u bytes of encrypted data in state %d\n",
       GCT_2s (t),
       (unsigned int) size,
       t->estate);

  switch (t->estate)
  {
  case CADET_TUNNEL_KEY_UNINITIALIZED:
  case CADET_TUNNEL_KEY_AX_RECV:
    /* We did not even SEND our KX, how can the other peer
       send us encrypted data? Must have been that we went
       down and the other peer still things we are up.
       Let's send it KX back. */
    GNUNET_STATISTICS_update (stats,
                              "# received encrypted without any KX",
                              1,
                              GNUNET_NO);
    if (NULL != t->kx_task)
    {
      GNUNET_SCHEDULER_cancel (t->kx_task);
      t->kx_task = NULL;
    }
    send_kx (t,
             ct,
             &t->ax);
    return;

  case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
    /* We send KX, and other peer send KX to us at the same time.
       Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
    GNUNET_STATISTICS_update (stats,
                              "# received encrypted without KX_AUTH",
                              1,
                              GNUNET_NO);
    if (NULL != t->kx_task)
    {
      GNUNET_SCHEDULER_cancel (t->kx_task);
      t->kx_task = NULL;
    }
    send_kx_auth (t,
                  ct,
                  &t->ax,
                  GNUNET_YES);
    return;

  case CADET_TUNNEL_KEY_AX_SENT:
    /* We did not get the KX of the other peer, but that
       might have been lost.  Send our KX again immediately. */
    GNUNET_STATISTICS_update (stats,
                              "# received encrypted without KX",
                              1,
                              GNUNET_NO);
    if (NULL != t->kx_task)
    {
      GNUNET_SCHEDULER_cancel (t->kx_task);
      t->kx_task = NULL;
    }
    send_kx (t,
             ct,
             &t->ax);
    return;

  case CADET_TUNNEL_KEY_AX_AUTH_SENT:
  /* Great, first payload, we might graduate to OK! */
  case CADET_TUNNEL_KEY_OK:
    /* We are up and running, all good. */
    break;
  }

  decrypted_size = -1;
  if (CADET_TUNNEL_KEY_OK == t->estate)
  {
    /* We have well-established key material available,
       try that. (This is the common case.) */
    decrypted_size = t_ax_decrypt_and_validate (&t->ax,
                                                cbuf,
                                                msg,
                                                size);
  }

  if ((-1 == decrypted_size) &&
      (NULL != t->unverified_ax))
  {
    /* We have un-authenticated KX material available. We should try
       this as a back-up option, in case the sender crashed and
       switched keys. */
    decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
                                                cbuf,
                                                msg,
                                                size);
    if (-1 != decrypted_size)
    {
      /* It worked! Treat this as authentication of the AX data! */
      cleanup_ax (&t->ax);
      t->ax = *t->unverified_ax;
      GNUNET_free (t->unverified_ax);
      t->unverified_ax = NULL;
    }
    if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
    {
      /* First time it worked, move tunnel into production! */
      GCT_change_estate (t,
                         CADET_TUNNEL_KEY_OK);
      if (NULL != t->send_task)
        GNUNET_SCHEDULER_cancel (t->send_task);
      t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
                                               t);
    }
  }
  if (NULL != t->unverified_ax)
  {
    /* We had unverified KX material that was useless; so increment
       counter and eventually move to ignore it.  Note that we even do
       this increment if we successfully decrypted with the old KX
       material and thus didn't even both with the new one.  This is
       the ideal case, as a malicious injection of bogus KX data
       basically only causes us to increment a counter a few times. */t->unverified_attempts++;
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Failed to decrypt message with unverified KX data %u times\n",
         t->unverified_attempts);
    if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
    {
      cleanup_ax (t->unverified_ax);
      GNUNET_free (t->unverified_ax);
      t->unverified_ax = NULL;
    }
  }

  if (-1 == decrypted_size)
  {
    /* Decryption failed for good, complain. */
    LOG (GNUNET_ERROR_TYPE_WARNING,
         "%s failed to decrypt and validate encrypted data, retrying KX\n",
         GCT_2s (t));
    GNUNET_STATISTICS_update (stats,
                              "# unable to decrypt",
                              1,
                              GNUNET_NO);
    if (NULL != t->kx_task)
    {
      GNUNET_SCHEDULER_cancel (t->kx_task);
      t->kx_task = NULL;
    }
    send_kx (t,
             ct,
             &t->ax);
    return;
  }
  GNUNET_STATISTICS_update (stats,
                            "# decrypted bytes",
                            decrypted_size,
                            GNUNET_NO);

  /* The MST will ultimately call #handle_decrypted() on each message. */
  t->current_ct = ct;
  GNUNET_break_op (GNUNET_OK ==
                   GNUNET_MST_from_buffer (t->mst,
                                           cbuf,
                                           decrypted_size,
                                           GNUNET_YES,
                                           GNUNET_NO));
  t->current_ct = NULL;
}


/**
 * Sends an already built message on a tunnel, encrypting it and
 * choosing the best connection if not provided.
 *
 * @param message Message to send. Function modifies it.
 * @param t Tunnel on which this message is transmitted.
 * @param cont Continuation to call once message is really sent.
 * @param cont_cls Closure for @c cont.
 * @param The ID of the channel we are using for sending.
 * @return Handle to cancel message
 */
struct CadetTunnelQueueEntry *
GCT_send (struct CadetTunnel *t,
          const struct GNUNET_MessageHeader *message,
          GCT_SendContinuation cont,
          void *cont_cls,
          struct GNUNET_CADET_ChannelTunnelNumber *ctn)
{
  struct CadetTunnelQueueEntry *tq;
  uint16_t payload_size;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
  struct CadetChannel *ch;

  if (NULL != ctn)
  {
    ch = lookup_channel (t,
                         *ctn);
    if ((NULL != ch) && GCCH_is_type_to_drop (ch, message))
    {
      GNUNET_break (0);
      return NULL;
    }
  }

  if (CADET_TUNNEL_KEY_OK != t->estate)
  {
    GNUNET_break (0);
    return NULL;
  }
  payload_size = ntohs (message->size);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Encrypting %u bytes for %s\n",
       (unsigned int) payload_size,
       GCT_2s (t));
  env = GNUNET_MQ_msg_extra (ax_msg,
                             payload_size,
                             GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
  t_ax_encrypt (&t->ax,
                &ax_msg[1],
                message,
                payload_size);
  GNUNET_STATISTICS_update (stats,
                            "# encrypted bytes",
                            payload_size,
                            GNUNET_NO);
  ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
  ax_msg->ax_header.PNs = htonl (t->ax.PNs);
  /* FIXME: we should do this once, not once per message;
     this is a point multiplication, and DHRs does not
     change all the time. */
  GNUNET_CRYPTO_ecdhe_key_get_public (&t->ax.DHRs,
                                      &ax_msg->ax_header.DHRs);
  t_h_encrypt (&t->ax,
               ax_msg);
  t_hmac (&ax_msg->ax_header,
          sizeof(struct GNUNET_CADET_AxHeader) + payload_size,
          0,
          &t->ax.HKs,
          &ax_msg->hmac);

  tq = GNUNET_malloc (sizeof(*tq));
  tq->t = t;
  tq->env = env;
  tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
  tq->cont = cont;
  tq->cont_cls = cont_cls;
  GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
                                    t->tq_tail,
                                    tq);
  if (NULL != t->send_task)
    GNUNET_SCHEDULER_cancel (t->send_task);
  t->send_task
    = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
                                t);
  return tq;
}


/**
 * 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 tq Handle to the queue entry to cancel.
 */
void
GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
{
  struct CadetTunnel *t = tq->t;

  GNUNET_CONTAINER_DLL_remove (t->tq_head,
                               t->tq_tail,
                               tq);
  GNUNET_MQ_discard (tq->env);
  GNUNET_free (tq);
}


/**
 * Iterate over all connections of a tunnel.
 *
 * @param t Tunnel whose connections to iterate.
 * @param iter Iterator.
 * @param iter_cls Closure for @c iter.
 */
void
GCT_iterate_connections (struct CadetTunnel *t,
                         GCT_ConnectionIterator iter,
                         void *iter_cls)
{
  struct CadetTConnection *n;

  for (struct CadetTConnection *ct = t->connection_ready_head;
       NULL != ct;
       ct = n)
  {
    n = ct->next;
    iter (iter_cls,
          ct);
  }
  for (struct CadetTConnection *ct = t->connection_busy_head;
       NULL != ct;
       ct = n)
  {
    n = ct->next;
    iter (iter_cls,
          ct);
  }
}


/**
 * Closure for #iterate_channels_cb.
 */
struct ChanIterCls
{
  /**
   * Function to call.
   */
  GCT_ChannelIterator iter;

  /**
   * Closure for @e iter.
   */
  void *iter_cls;
};


/**
 * Helper function for #GCT_iterate_channels.
 *
 * @param cls the `struct ChanIterCls`
 * @param key unused
 * @param value a `struct CadetChannel`
 * @return #GNUNET_OK
 */
static int
iterate_channels_cb (void *cls,
                     uint32_t key,
                     void *value)
{
  struct ChanIterCls *ctx = cls;
  struct CadetChannel *ch = value;

  ctx->iter (ctx->iter_cls,
             ch);
  return GNUNET_OK;
}


/**
 * Iterate over all channels of a tunnel.
 *
 * @param t Tunnel whose channels to iterate.
 * @param iter Iterator.
 * @param iter_cls Closure for @c iter.
 */
void
GCT_iterate_channels (struct CadetTunnel *t,
                      GCT_ChannelIterator iter,
                      void *iter_cls)
{
  struct ChanIterCls ctx;

  ctx.iter = iter;
  ctx.iter_cls = iter_cls;
  GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
                                           &iterate_channels_cb,
                                           &ctx);
}


/**
 * Call #GCCH_debug() on a channel.
 *
 * @param cls points to the log level to use
 * @param key unused
 * @param value the `struct CadetChannel` to dump
 * @return #GNUNET_OK (continue iteration)
 */
static int
debug_channel (void *cls,
               uint32_t key,
               void *value)
{
  const enum GNUNET_ErrorType *level = cls;
  struct CadetChannel *ch = value;

  GCCH_debug (ch, *level);
  return GNUNET_OK;
}


#define LOG2(level, ...) GNUNET_log_from_nocheck (level, "cadet-tun", \
                                                  __VA_ARGS__)


/**
 * Log all possible info about the tunnel state.
 *
 * @param t Tunnel to debug.
 * @param level Debug level to use.
 */
void
GCT_debug (const struct CadetTunnel *t,
           enum GNUNET_ErrorType level)
{
#if ! defined(GNUNET_CULL_LOGGING)
  struct CadetTConnection *iter_c;
  int do_log;

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

  LOG2 (level,
        "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
        GCT_2s (t),
        estate2s (t->estate),
        t->tq_len,
        GCT_count_any_connections (t));
  LOG2 (level,
        "TTT channels:\n");
  GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
                                           &debug_channel,
                                           &level);
  LOG2 (level,
        "TTT connections:\n");
  for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
    GCC_debug (iter_c->cc,
               level);
  for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
    GCC_debug (iter_c->cc,
               level);

  LOG2 (level,
        "TTT TUNNEL END\n");
#endif
}


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