summaryrefslogtreecommitdiff
path: root/src/cadet/gnunet-service-cadet_peer.c
blob: f99ce482fa31562ffe6ace0d25e70d257f90c7d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
/*
     This file is part of GNUnet.
     Copyright (C) 2013, 2015 Christian Grothoff (and other contributing authors)

     GNUnet is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published
     by the Free Software Foundation; either version 3, or (at your
     option) any later version.

     GNUnet is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with GNUnet; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
     Boston, MA 02111-1307, USA.
*/
/**
 * @file cadet/gnunet-service-cadet_peer.c
 * @brief GNUnet CADET service connection handling
 * @author Bartlomiej Polot
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_signatures.h"
#include "gnunet_transport_service.h"
#include "gnunet_core_service.h"
#include "gnunet_statistics_service.h"
#include "cadet_protocol.h"
#include "gnunet-service-cadet_peer.h"
#include "gnunet-service-cadet_dht.h"
#include "gnunet-service-cadet_connection.h"
#include "gnunet-service-cadet_tunnel.h"
#include "cadet_path.h"

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


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

/**
 * Struct containing info about a queued transmission to this peer
 */
struct CadetPeerQueue
{
  /**
   * DLL next
   */
  struct CadetPeerQueue *next;

  /**
   * DLL previous
   */
  struct CadetPeerQueue *prev;

  /**
   * Peer this transmission is directed to.
   */
  struct CadetPeer *peer;

  /**
   * Connection this message belongs to.
   */
  struct CadetConnection *c;

  /**
   * Is FWD in c?
   */
  int fwd;

  /**
   * Pointer to info stucture used as cls.
   */
  void *cls;

  /**
   * Type of message
   */
  uint16_t type;

  /**
   * Type of message
   */
  uint16_t payload_type;

  /**
   * Type of message
   */
  uint32_t payload_id;

  /**
   * Size of the message
   */
  size_t size;

  /**
   * Set when this message starts waiting for CORE.
   */
  struct GNUNET_TIME_Absolute start_waiting;

  /**
   * Function to call on sending.
   */
  GCP_sent cont;

  /**
   * Closure for callback.
   */
  void *cont_cls;
};


/**
 * Struct containing all information regarding a given peer
 */
struct CadetPeer
{
  /**
   * ID of the peer
   */
  GNUNET_PEER_Id id;

  /**
   * Last time we heard from this peer
   */
  struct GNUNET_TIME_Absolute last_contact;

  /**
   * Paths to reach the peer, ordered by ascending hop count
   */
  struct CadetPeerPath *path_head;

  /**
   * Paths to reach the peer, ordered by ascending hop count
   */
  struct CadetPeerPath *path_tail;

  /**
   * Handle to stop the DHT search for paths to this peer
   */
  struct GCD_search_handle *search_h;

  /**
   * Handle to stop the DHT search for paths to this peer
   */
  struct GNUNET_SCHEDULER_Task *search_delayed;

  /**
   * Tunnel to this peer, if any.
   */
  struct CadetTunnel *tunnel;

  /**
   * Connections that go through this peer; indexed by tid.
   */
  struct GNUNET_CONTAINER_MultiHashMap *connections;

  /**
   * Handle for queued transmissions
   */
  struct GNUNET_CORE_TransmitHandle *core_transmit;

  /**
   * Timestamp
   */
  struct GNUNET_TIME_Absolute tmt_time;

  /**
   * Transmission queue to core DLL head
   */
  struct CadetPeerQueue *queue_head;

  /**
   * Transmission queue to core DLL tail
   */
  struct CadetPeerQueue *queue_tail;

  /**
   * How many messages are in the queue to this peer.
   */
  unsigned int queue_n;

  /**
   * Hello message.
   */
  struct GNUNET_HELLO_Message* hello;
};


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

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

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

/**
 * Local peer own ID (short)
 */
extern GNUNET_PEER_Id myid;

/**
 * Peers known, indexed by PeerIdentity, values of type `struct CadetPeer`.
 */
static struct GNUNET_CONTAINER_MultiPeerMap *peers;

/**
 * How many peers do we want to remember?
 */
static unsigned long long max_peers;

/**
 * Percentage of messages that will be dropped (for test purposes only).
 */
static unsigned long long drop_percent;

/**
 * Handle to communicate with core.
 */
static struct GNUNET_CORE_Handle *core_handle;

/**
 * Handle to try to start new connections.
 */
static struct GNUNET_TRANSPORT_Handle *transport_handle;

/**
 * Shutdown falg.
 */
static int in_shutdown;


/******************************************************************************/
/*****************************     DEBUG      *********************************/
/******************************************************************************/

/**
 * Log all kinds of info about the queueing status of a peer.
 *
 * @param p Peer whose queue to show.
 * @param level Error level to use for logging.
 */
static void
queue_debug (const struct CadetPeer *p, enum GNUNET_ErrorType level)
{
  struct GNUNET_TIME_Relative core_wait_time;
  struct CadetPeerQueue *q;
  int do_log;

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

  LOG2 (level, "QQQ Message queue towards %s\n", GCP_2s (p));
  LOG2 (level, "QQQ  queue length: %u\n", p->queue_n);
  LOG2 (level, "QQQ  core tmt rdy: %p\n", p->core_transmit);
  if (NULL != p->core_transmit)
  {
    core_wait_time = GNUNET_TIME_absolute_get_duration (p->tmt_time);
    LOG2 (level, "QQQ  core called %s ago\n",
          GNUNET_STRINGS_relative_time_to_string (core_wait_time, GNUNET_NO));
  }
  for (q = p->queue_head; NULL != q; q = q->next)
  {
    LOG2 (level, "QQQ  - %s %s on %s\n",
         GC_m2s (q->type), GC_f2s (q->fwd), GCC_2s (q->c));
    LOG2 (level, "QQQ    payload %s, %u\n",
         GC_m2s (q->payload_type), q->payload_id);
    LOG2 (level, "QQQ    size: %u bytes\n", q->size);
  }

  LOG2 (level, "QQQ End queue towards %s\n", GCP_2s (p));
}


/**
 * Log all kinds of info about a peer.
 *
 * @param peer Peer.
 */
void
GCP_debug (const struct CadetPeer *p, enum GNUNET_ErrorType level)
{
  struct CadetPeerPath *path;
  unsigned int conns;
  int do_log;

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

  if (NULL == p)
  {
    LOG2 (level, "PPP DEBUG PEER NULL\n");
    return;
  }

  LOG2 (level, "PPP DEBUG PEER %s\n", GCP_2s (p));
  LOG2 (level, "PPP last contact %s\n",
       GNUNET_STRINGS_absolute_time_to_string (p->last_contact));
  for (path = p->path_head; NULL != path; path = path->next)
  {
    char *s;

    s = path_2s (path);
    LOG2 (level, "PPP path: %s\n", s);
    GNUNET_free (s);
  }

  LOG2 (level, "PPP core transmit handle %p\n", p->core_transmit);
  LOG2 (level, "PPP DHT GET handle %p\n", p->search_h);
  conns = 0;
  if (NULL != p->connections)
    conns += GNUNET_CONTAINER_multihashmap_size (p->connections);
  LOG2 (level, "PPP # connections over link to peer: %u\n", conns);
  queue_debug (p, level);
  LOG2 (level, "PPP DEBUG END\n");
}


/******************************************************************************/
/*****************************  CORE HELPERS  *********************************/
/******************************************************************************/


/**
 * Iterator to notify all connections of a broken link. Mark connections
 * to destroy after all traffic has been sent.
 *
 * @param cls Closure (peer disconnected).
 * @param key Current key code (peer id).
 * @param value Value in the hash map (connection).
 *
 * @return #GNUNET_YES to continue to iterate.
 */
static int
notify_broken (void *cls,
               const struct GNUNET_HashCode *key,
               void *value)
{
  struct CadetPeer *peer = cls;
  struct CadetConnection *c = value;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Notifying %s due to %s\n",
       GCC_2s (c),
       GCP_2s (peer));
  GCC_notify_broken (c,
                     peer);
  return GNUNET_YES;
}


/**
 * Remove the direct path to the peer.
 *
 * @param peer Peer to remove the direct path from.
 *
 */
static struct CadetPeerPath *
pop_direct_path (struct CadetPeer *peer)
{
  struct CadetPeerPath *iter;

  for (iter = peer->path_head; NULL != iter; iter = iter->next)
  {
    if (2 >= iter->length)
    {
      GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, iter);
      return iter;
    }
  }
  return NULL;
}


/******************************************************************************/
/***************************** CORE CALLBACKS *********************************/
/******************************************************************************/


/**
 * Method called whenever a given peer connects.
 *
 * @param cls closure
 * @param peer peer identity this notification is about
 */
static void
core_connect (void *cls,
              const struct GNUNET_PeerIdentity *peer)
{
  struct CadetPeer *mp;
  struct CadetPeerPath *path;
  char own_id[16];

  GNUNET_snprintf (own_id,
                   sizeof (own_id),
                   "%s",
                   GNUNET_i2s (&my_full_id));
  mp = GCP_get (peer);
  if (myid == mp->id)
  {
    LOG (GNUNET_ERROR_TYPE_INFO,
         "CONNECTED %s (self)\n",
         own_id);
    path = path_new (1);
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_INFO,
         "CONNECTED %s <= %s\n",
         own_id,
         GNUNET_i2s (peer));
    path = path_new (2);
    path->peers[1] = mp->id;
    GNUNET_PEER_change_rc (mp->id, 1);
  }
  path->peers[0] = myid;
  GNUNET_PEER_change_rc (myid, 1);
  GCP_add_path (mp, path, GNUNET_YES);
  GNUNET_STATISTICS_update (stats,
                            "# peers",
                            1,
                            GNUNET_NO);
  GNUNET_assert (NULL == mp->connections);
  mp->connections = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_NO);

  if ( (NULL != GCP_get_tunnel (mp)) &&
       (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, peer)) )
    GCP_connect (mp);
}


/**
 * Method called whenever a peer disconnects.
 *
 * @param cls closure
 * @param peer peer identity this notification is about
 */
static void
core_disconnect (void *cls,
                 const struct GNUNET_PeerIdentity *peer)
{
  struct CadetPeer *p;
  struct CadetPeerPath *direct_path;
  char own_id[16];

  strncpy (own_id, GNUNET_i2s (&my_full_id), 15);
  p = GNUNET_CONTAINER_multipeermap_get (peers, peer);
  if (NULL == p)
  {
    GNUNET_break (GNUNET_YES == in_shutdown);
    return;
  }
  if (myid == p->id)
    LOG (GNUNET_ERROR_TYPE_INFO,
         "DISCONNECTED %s (self)\n",
         own_id);
  else
    LOG (GNUNET_ERROR_TYPE_INFO,
         "DISCONNECTED %s <= %s\n",
         own_id, GNUNET_i2s (peer));
  direct_path = pop_direct_path (p);
  GNUNET_CONTAINER_multihashmap_iterate (p->connections,
                                         &notify_broken,
                                         p);
  GNUNET_CONTAINER_multihashmap_destroy (p->connections);
  p->connections = NULL;
  if (NULL != p->core_transmit)
  {
    GNUNET_CORE_notify_transmit_ready_cancel (p->core_transmit);
    p->core_transmit = NULL;
    p->tmt_time.abs_value_us = 0;
  }
  GNUNET_STATISTICS_update (stats,
                            "# peers",
                            -1,
                            GNUNET_NO);
  path_destroy (direct_path);
}


/**
 * Functions to handle messages from core
 */
static struct GNUNET_CORE_MessageHandler core_handlers[] = {
  {&GCC_handle_create, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE, 0},
  {&GCC_handle_confirm, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK,
    sizeof (struct GNUNET_CADET_ConnectionACK)},
  {&GCC_handle_broken, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN,
    sizeof (struct GNUNET_CADET_ConnectionBroken)},
  {&GCC_handle_destroy, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY,
    sizeof (struct GNUNET_CADET_ConnectionDestroy)},
  {&GCC_handle_ack, GNUNET_MESSAGE_TYPE_CADET_ACK,
    sizeof (struct GNUNET_CADET_ACK)},
  {&GCC_handle_poll, GNUNET_MESSAGE_TYPE_CADET_POLL,
    sizeof (struct GNUNET_CADET_Poll)},
  {&GCC_handle_kx, GNUNET_MESSAGE_TYPE_CADET_KX, 0},
  {&GCC_handle_encrypted, GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED, 0},
  {&GCC_handle_encrypted, GNUNET_MESSAGE_TYPE_CADET_AX, 0},
  {NULL, 0, 0}
};


/**
 * To be called on core init/fail.
 *
 * @param cls Closure (config)
 * @param identity the public identity of this peer
 */
static void
core_init (void *cls,
           const struct GNUNET_PeerIdentity *identity)
{
  const struct GNUNET_CONFIGURATION_Handle *c = cls;
  static int i = 0;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
  if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
  {
    LOG (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
    LOG (GNUNET_ERROR_TYPE_ERROR, " core id %s\n", GNUNET_i2s (identity));
    LOG (GNUNET_ERROR_TYPE_ERROR, " my id %s\n", GNUNET_i2s (&my_full_id));
    GNUNET_CORE_disconnect (core_handle);
    core_handle = GNUNET_CORE_connect (c, /* Main configuration */
                                       NULL,      /* Closure passed to CADET functions */
                                       &core_init,        /* Call core_init once connected */
                                       &core_connect,     /* Handle connects */
                                       &core_disconnect,  /* remove peers on disconnects */
                                       NULL,      /* Don't notify about all incoming messages */
                                       GNUNET_NO, /* For header only in notification */
                                       NULL,      /* Don't notify about all outbound messages */
                                       GNUNET_NO, /* For header-only out notification */
                                       core_handlers);    /* Register these handlers */
    if (10 < i++)
      GNUNET_assert (0);
  }
  GML_start ();
}


/**
  * Core callback to write a pre-constructed data packet to core buffer
  *
  * @param cls Closure (CadetTransmissionDescriptor with data in "data" member).
  * @param size Number of bytes available in buf.
  * @param buf Where the to write the message.
  *
  * @return number of bytes written to buf
  */
static size_t
send_core_data_raw (void *cls, size_t size, void *buf)
{
  struct GNUNET_MessageHeader *msg = cls;
  size_t total_size;

  GNUNET_assert (NULL != msg);
  total_size = ntohs (msg->size);

  if (total_size > size)
  {
    GNUNET_break (0);
    return 0;
  }
  memcpy (buf, msg, total_size);
  GNUNET_free (cls);
  return total_size;
}


/**
 * Function to send a create connection message to a peer.
 *
 * @param c Connection to create.
 * @param size number of bytes available in buf
 * @param buf where the callee should write the message
 * @return number of bytes written to buf
 */
static size_t
send_core_connection_create (struct CadetConnection *c, size_t size, void *buf)
{
  struct GNUNET_CADET_ConnectionCreate *msg;
  struct GNUNET_PeerIdentity *peer_ptr;
  const struct CadetPeerPath *p = GCC_get_path (c);
  size_t size_needed;
  int i;

  if (NULL == p)
    return 0;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
  size_needed =
      sizeof (struct GNUNET_CADET_ConnectionCreate) +
      p->length * sizeof (struct GNUNET_PeerIdentity);

  if (size < size_needed || NULL == buf)
  {
    GNUNET_break (0);
    return 0;
  }
  msg = (struct GNUNET_CADET_ConnectionCreate *) buf;
  msg->header.size = htons (size_needed);
  msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE);
  msg->cid = *GCC_get_id (c);

  peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
  for (i = 0; i < p->length; i++)
  {
    GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
  }

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "CONNECTION CREATE (%u bytes long) sent!\n",
       size_needed);
  return size_needed;
}


/**
 * Creates a path ack message in buf and frees all unused resources.
 *
 * @param c Connection to send an ACK on.
 * @param size number of bytes available in buf
 * @param buf where the callee should write the message
 *
 * @return number of bytes written to buf
 */
static size_t
send_core_connection_ack (struct CadetConnection *c, size_t size, void *buf)
{
  struct GNUNET_CADET_ConnectionACK *msg = buf;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
  if (sizeof (struct GNUNET_CADET_ConnectionACK) > size)
  {
    GNUNET_break (0);
    return 0;
  }
  msg->header.size = htons (sizeof (struct GNUNET_CADET_ConnectionACK));
  msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK);
  msg->cid = *GCC_get_id (c);

  LOG (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
  return sizeof (struct GNUNET_CADET_ConnectionACK);
}


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


/**
 * Get priority for a queued message.
 *
 * @param q Queued message
 *
 * @return CORE priority to use.
 */
static enum GNUNET_CORE_Priority
get_priority (struct CadetPeerQueue *q)
{
  enum GNUNET_CORE_Priority low;
  enum GNUNET_CORE_Priority high;

  if (NULL == q)
  {
    GNUNET_break (0);
    return GNUNET_CORE_PRIO_BACKGROUND;
  }

  /* Relayed traffic has lower priority, our own traffic has higher */
  if (NULL == q->c || GNUNET_NO == GCC_is_origin (q->c, q->fwd))
  {
    low = GNUNET_CORE_PRIO_BEST_EFFORT;
    high = GNUNET_CORE_PRIO_URGENT;
  }
  else
  {
    low = GNUNET_CORE_PRIO_URGENT;
    high = GNUNET_CORE_PRIO_CRITICAL_CONTROL;
  }

  /* Bulky payload has lower priority, control traffic has higher. */
  if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == q->type
      || GNUNET_MESSAGE_TYPE_CADET_AX == q->type)
    return low;
  else
    return high;
}


/**
 * Destroy the peer_info and free any allocated resources linked to it
 *
 * @param peer The peer_info to destroy.
 * @return #GNUNET_OK on success
 */
static int
peer_destroy (struct CadetPeer *peer)
{
  struct GNUNET_PeerIdentity id;
  struct CadetPeerPath *p;
  struct CadetPeerPath *nextp;

  GNUNET_PEER_resolve (peer->id, &id);
  GNUNET_PEER_change_rc (peer->id, -1);

  LOG (GNUNET_ERROR_TYPE_INFO,
       "destroying peer %s\n",
       GNUNET_i2s (&id));

  if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove (peers, &id, peer))
  {
    GNUNET_break (0);
    LOG (GNUNET_ERROR_TYPE_WARNING, " peer not in peermap!!\n");
  }
  GCP_stop_search (peer);
  p = peer->path_head;
  while (NULL != p)
  {
    nextp = p->next;
    GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
    path_destroy (p);
    p = nextp;
  }
  if (NULL != peer->tunnel)
    GCT_destroy_empty (peer->tunnel);
  if (NULL != peer->connections)
  {
    GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (peer->connections));
    GNUNET_CONTAINER_multihashmap_destroy (peer->connections);
  }
  GNUNET_free_non_null (peer->hello);
  GNUNET_free (peer);
  return GNUNET_OK;
}


/**
 * Iterator over peer hash map entries to destroy the peer during in_shutdown.
 *
 * @param cls closure
 * @param key current key code
 * @param value value in the hash map
 * @return #GNUNET_YES if we should continue to iterate,
 *         #GNUNET_NO if not.
 */
static int
shutdown_peer (void *cls,
               const struct GNUNET_PeerIdentity *key,
               void *value)
{
  struct CadetPeer *p = value;
  struct CadetTunnel *t = p->tunnel;

  if (NULL != t)
    GCT_destroy (t);
  p->tunnel = NULL;
  peer_destroy (p);
  return GNUNET_YES;
}



/**
 * Check if peer is searching for a path (either active or delayed search).
 *
 * @param peer Peer to check
 * @return #GNUNET_YES if there is a search active.
 *         #GNUNET_NO otherwise.
 */
static int
is_searching (const struct CadetPeer *peer)
{
  return (NULL == peer->search_h && NULL == peer->search_delayed) ?
         GNUNET_NO : GNUNET_YES;
}


/**
 * @brief Start a search for a peer.
 *
 * @param cls Closure (Peer to search for).
 * @param tc Task context.
 */
static void
delayed_search (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct CadetPeer *peer = cls;

  peer->search_delayed = NULL;

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

  GCP_start_search (peer);
}


/**
 * Returns if peer is used (has a tunnel or is neighbor).
 *
 * @param peer Peer to check.
 * @return #GNUNET_YES if peer is in use.
 */
static int
peer_is_used (struct CadetPeer *peer)
{
  struct CadetPeerPath *p;

  if (NULL != peer->tunnel)
    return GNUNET_YES;

  for (p = peer->path_head; NULL != p; p = p->next)
  {
    if (p->length < 3)
      return GNUNET_YES;
  }
    return GNUNET_NO;
}


/**
 * Iterator over all the peers to get the oldest timestamp.
 *
 * @param cls Closure (unsued).
 * @param key ID of the peer.
 * @param value Peer_Info of the peer.
 */
static int
peer_get_oldest (void *cls,
                 const struct GNUNET_PeerIdentity *key,
                 void *value)
{
  struct CadetPeer *p = value;
  struct GNUNET_TIME_Absolute *abs = cls;

  /* Don't count active peers */
  if (GNUNET_YES == peer_is_used (p))
    return GNUNET_YES;

  if (abs->abs_value_us < p->last_contact.abs_value_us)
    abs->abs_value_us = p->last_contact.abs_value_us;

  return GNUNET_YES;
}


/**
 * Iterator over all the peers to remove the oldest entry.
 *
 * @param cls Closure (unsued).
 * @param key ID of the peer.
 * @param value Peer_Info of the peer.
 */
static int
peer_timeout (void *cls,
              const struct GNUNET_PeerIdentity *key,
              void *value)
{
  struct CadetPeer *p = value;
  struct GNUNET_TIME_Absolute *abs = cls;

  LOG (GNUNET_ERROR_TYPE_WARNING,
       "peer %s timeout\n", GNUNET_i2s (key));

  if (p->last_contact.abs_value_us == abs->abs_value_us &&
      GNUNET_NO == peer_is_used (p))
  {
    peer_destroy (p);
    return GNUNET_NO;
  }
    return GNUNET_YES;
}


/**
 * Delete oldest unused peer.
 */
static void
peer_delete_oldest (void)
{
  struct GNUNET_TIME_Absolute abs;

  abs = GNUNET_TIME_UNIT_FOREVER_ABS;

  GNUNET_CONTAINER_multipeermap_iterate (peers,
                                         &peer_get_oldest,
                                         &abs);
  GNUNET_CONTAINER_multipeermap_iterate (peers,
                                         &peer_timeout,
                                         &abs);
}


/**
 * Choose the best (yet unused) path towards a peer,
 * considering the tunnel properties.
 *
 * @param peer The destination peer.
 * @return Best current known path towards the peer, if any.
 */
static struct CadetPeerPath *
peer_get_best_path (const struct CadetPeer *peer)
{
  struct CadetPeerPath *best_p;
  struct CadetPeerPath *p;
  unsigned int best_cost;
  unsigned int cost;

  best_cost = UINT_MAX;
  best_p = NULL;
  for (p = peer->path_head; NULL != p; p = p->next)
  {
    if (GNUNET_NO == path_is_valid (p))
      continue; /* Don't use invalid paths. */
    if (GNUNET_YES == GCT_is_path_used (peer->tunnel, p))
      continue; /* If path is already in use, skip it. */

    if ((cost = GCT_get_path_cost (peer->tunnel, p)) < best_cost)
    {
      best_cost = cost;
      best_p = p;
    }
  }
  return best_p;
}


/**
 * Is this queue element sendable?
 *
 * - All management traffic is always sendable.
 * - For payload traffic, check the connection flow control.
 *
 * @param q Queue element to inspect.
 * @return #GNUNET_YES if it is sendable, #GNUNET_NO otherwise.
 */
static int
queue_is_sendable (struct CadetPeerQueue *q)
{
  /* Is PID-independent? */
  switch (q->type)
  {
    case GNUNET_MESSAGE_TYPE_CADET_ACK:
    case GNUNET_MESSAGE_TYPE_CADET_POLL:
    case GNUNET_MESSAGE_TYPE_CADET_KX:
    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
      return GNUNET_YES;

    case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
    case GNUNET_MESSAGE_TYPE_CADET_AX:
      break;

    default:
      GNUNET_break (0);
  }

  return GCC_is_sendable (q->c, q->fwd);
}


/**
 * Get first sendable message.
 *
 * @param peer The destination peer.
 *
 * @return First transmittable message, if any. Otherwise, NULL.
 */
static struct CadetPeerQueue *
peer_get_first_message (const struct CadetPeer *peer)
{
  struct CadetPeerQueue *q;

  for (q = peer->queue_head; NULL != q; q = q->next)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking q:%p on c:%s\n", q, GCC_2s (q->c));
    if (queue_is_sendable (q))
      return q;
  }

  return NULL;
}


/**
 * Function to process paths received for a new peer addition. The recorded
 * paths form the initial tunnel, which can be optimized later.
 * Called on each result obtained for the DHT search.
 *
 * @param cls closure
 * @param path
 */
static void
search_handler (void *cls, const struct CadetPeerPath *path)
{
  struct CadetPeer *peer = cls;
  unsigned int connection_count;

  GCP_add_path_to_all (path, GNUNET_NO);

  /* Count connections */
  connection_count = GCT_count_connections (peer->tunnel);

  /* If we already have our minimum (or more) connections, it's enough */
  if (CONNECTIONS_PER_TUNNEL <= connection_count)
    return;

  if (CADET_TUNNEL_SEARCHING == GCT_get_cstate (peer->tunnel))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
    GCP_connect (peer);
  }
}


/**
 * Adjust core requested size to accomodate an ACK.
 *
 * @param message_size Requested size.
 *
 * @return Size enough to fit @c message_size and an ACK.
 */
static size_t
get_core_size (size_t message_size)
{
  return message_size + sizeof (struct GNUNET_CADET_ACK);
}


/**
 * Fill a core buffer with the appropriate data for the queued message.
 *
 * @param queue Queue element for the message.
 * @param buf Core buffer to fill.
 * @param size Size remaining in @c buf.
 * @param[out] pid In case its an encrypted payload, set payload.
 *
 * @return Bytes written to @c buf.
 */
static size_t
fill_buf (struct CadetPeerQueue *queue, void *buf, size_t size, uint32_t *pid)
{
  struct CadetConnection *c = queue->c;
  size_t msg_size;

  switch (queue->type)
  {
    case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
      *pid = GCC_get_pid (queue->c, queue->fwd);
      LOG (GNUNET_ERROR_TYPE_DEBUG, "  otr payload ID %u\n", *pid);
      msg_size = send_core_data_raw (queue->cls, size, buf);
      ((struct GNUNET_CADET_Encrypted *) buf)->pid = htonl (*pid);
      break;
    case GNUNET_MESSAGE_TYPE_CADET_AX:
      *pid = GCC_get_pid (queue->c, queue->fwd);
      LOG (GNUNET_ERROR_TYPE_DEBUG, "  ax payload ID %u\n", *pid);
      msg_size = send_core_data_raw (queue->cls, size, buf);
      ((struct GNUNET_CADET_AX *) buf)->pid = htonl (*pid);
      break;
    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
    case GNUNET_MESSAGE_TYPE_CADET_KX:
    case GNUNET_MESSAGE_TYPE_CADET_ACK:
    case GNUNET_MESSAGE_TYPE_CADET_POLL:
      LOG (GNUNET_ERROR_TYPE_DEBUG, "  raw %s\n", GC_m2s (queue->type));
      msg_size = send_core_data_raw (queue->cls, size, buf);
      break;
    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
      LOG (GNUNET_ERROR_TYPE_DEBUG, "  path create\n");
      if (GCC_is_origin (c, GNUNET_YES))
        msg_size = send_core_connection_create (c, size, buf);
      else
        msg_size = send_core_data_raw (queue->cls, size, buf);
      break;
    case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
      LOG (GNUNET_ERROR_TYPE_DEBUG, "  path ack\n");
      if (GCC_is_origin (c, GNUNET_NO) ||
          GCC_is_origin (c, GNUNET_YES))
      {
        msg_size = send_core_connection_ack (c, size, buf);
      }
      else
      {
        msg_size = send_core_data_raw (queue->cls, size, buf);
      }
      break;
    case GNUNET_MESSAGE_TYPE_CADET_DATA:
    case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
    case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
      /* This should be encapsulted */
      msg_size = 0;
      GNUNET_assert (0);
      break;
    default:
      GNUNET_break (0);
      LOG (GNUNET_ERROR_TYPE_WARNING, "  type unknown: %u\n", queue->type);
      msg_size = 0;
  }

  GNUNET_assert (size >= msg_size);

  return msg_size;
}


/**
 * Core callback to write a queued packet to core buffer
 *
 * @param cls Closure (peer info).
 * @param size Number of bytes available in buf.
 * @param buf Where the to write the message.
 *
 * @return number of bytes written to buf
 */
static size_t
queue_send (void *cls, size_t size, void *buf)
{
  struct CadetPeer *peer = cls;
  struct CadetConnection *c;
  struct CadetPeerQueue *queue;
  struct GNUNET_TIME_Relative core_wait_time;
  const struct GNUNET_PeerIdentity *dst_id;
  size_t msg_size;
  size_t total_size;
  size_t rest;
  char *dst;
  uint32_t pid;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
  LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
  LOG (GNUNET_ERROR_TYPE_DEBUG, "Queue send towards %s (max %u)\n",
       GCP_2s (peer), size);

  /* Sanity checking */
  if (NULL == buf || 0 == size)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  not allowed/\n");
    if (GNUNET_NO == in_shutdown)
    {
      queue = peer_get_first_message (peer);
      dst_id = GNUNET_PEER_resolve2 (peer->id);
      peer->core_transmit =
          GNUNET_CORE_notify_transmit_ready (core_handle,
                                            GNUNET_NO, get_priority (queue),
                                            GNUNET_TIME_UNIT_FOREVER_REL,
                                            dst_id,
                                            get_core_size (queue->size),
                                            &queue_send,
                                            peer);
      peer->tmt_time = GNUNET_TIME_absolute_get ();
    }
    else
    {
      peer->core_transmit = NULL;
      peer->tmt_time.abs_value_us = 0;
    }
    return 0;
  }

  /* Init */
  rest = size;
  total_size = 0;
  dst = (char *) buf;
  pid = 0;
  peer->core_transmit = NULL;
  queue = peer_get_first_message (peer);
  if (NULL == queue)
  {
    GNUNET_break (0); /* Core tmt_rdy should've been canceled */
    peer->tmt_time.abs_value_us = 0;
    return 0;
  }
  core_wait_time = GNUNET_TIME_absolute_get_duration (peer->tmt_time);
  if (core_wait_time.rel_value_us >= 1000000)
  {
    LOG (GNUNET_ERROR_TYPE_ERROR, " core wait time %s > 1 second\n",
         GNUNET_STRINGS_relative_time_to_string (core_wait_time, GNUNET_NO));
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, " core wait time %s\n",
         GNUNET_STRINGS_relative_time_to_string (core_wait_time, GNUNET_NO));
  }
  peer->tmt_time.abs_value_us = 0;

  /* Copy all possible messages to the core buffer */
  while (NULL != queue && rest >= queue->size)
  {
    c = queue->c;

    LOG (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s %s\n",
         GCC_2s (c), GC_f2s(queue->fwd));
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  size %u ok (%u/%u)\n",
         queue->size, total_size, size);

    msg_size = fill_buf (queue, (void *) dst, size, &pid);

    if (0 < drop_percent &&
        GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
    {
      LOG (GNUNET_ERROR_TYPE_WARNING, "DD %s (%s %u) on connection %s %s\n",
           GC_m2s (queue->type), GC_m2s (queue->payload_type),
           queue->payload_id, GCC_2s (c), GC_f2s (queue->fwd));
      msg_size = 0;
    }
    else
    {
      LOG (GNUNET_ERROR_TYPE_INFO,
           "snd %s (%s %4u) on connection %s (%p) %s (size %u)\n",
           GC_m2s (queue->type), GC_m2s (queue->payload_type),
           queue->payload_id, GCC_2s (c), c, GC_f2s (queue->fwd), msg_size);
    }
    total_size += msg_size;
    rest -= msg_size;
    dst = &dst[msg_size];
    msg_size = 0;

    /* Free queue, but cls was freed by send_core_* in fill_buf. */
    (void) GCP_queue_destroy (queue, GNUNET_NO, GNUNET_YES, pid);

    /* Next! */
    queue = peer_get_first_message (peer);
  }

  /* If more data in queue, send next */
  if (NULL != queue)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  more data! (%u)\n", queue->size);
    if (NULL == peer->core_transmit)
    {
      dst_id = GNUNET_PEER_resolve2 (peer->id);
      peer->core_transmit =
          GNUNET_CORE_notify_transmit_ready (core_handle,
                                             GNUNET_NO, get_priority (queue),
                                             GNUNET_TIME_UNIT_FOREVER_REL,
                                             dst_id,
                                             get_core_size (queue->size),
                                             &queue_send,
                                             peer);
      peer->tmt_time = GNUNET_TIME_absolute_get ();
      queue->start_waiting = GNUNET_TIME_absolute_get ();
    }
    else
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, "*   tmt rdy called somewhere else\n");
    }
//     GCC_start_poll (); FIXME needed?
  }
  else
  {
//     GCC_stop_poll(); FIXME needed?
  }

  LOG (GNUNET_ERROR_TYPE_DEBUG, "  return %d\n", total_size);
  queue_debug (peer, GNUNET_ERROR_TYPE_DEBUG);

  return total_size;
}


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


/**
 * Free a transmission that was already queued with all resources
 * associated to the request.
 *
 * If connection was marked to be destroyed, and this was the last queued
 * message on it, the connection will be free'd as a result.
 *
 * @param queue Queue handler to cancel.
 * @param clear_cls Is it necessary to free associated cls?
 * @param sent Was it really sent? (Could have been canceled)
 * @param pid PID, if relevant (was sent and was a payload message).
 *
 * @return #GNUNET_YES if connection was destroyed as a result,
 *         #GNUNET_NO otherwise.
 */
int
GCP_queue_destroy (struct CadetPeerQueue *queue, int clear_cls,
                   int sent, uint32_t pid)
{
  struct CadetPeer *peer;
  int connection_destroyed;

  peer = queue->peer;
  LOG (GNUNET_ERROR_TYPE_DEBUG, "queue destroy %s\n", GC_m2s (queue->type));
  if (GNUNET_YES == clear_cls)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, " free cls\n");
    switch (queue->type)
    {
      case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
        LOG (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
        /* fall through */
      case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
      case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
      case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
      case GNUNET_MESSAGE_TYPE_CADET_KX:
      case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
      case GNUNET_MESSAGE_TYPE_CADET_AX:
      case GNUNET_MESSAGE_TYPE_CADET_ACK:
      case GNUNET_MESSAGE_TYPE_CADET_POLL:
        GNUNET_free_non_null (queue->cls);
        break;

      default:
        GNUNET_break (0);
        LOG (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
             GC_m2s (queue->type));
    }
  }
  GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);

  if (queue->type != GNUNET_MESSAGE_TYPE_CADET_ACK &&
      queue->type != GNUNET_MESSAGE_TYPE_CADET_POLL)
  {
    peer->queue_n--;
  }

  if (NULL != queue->cont)
  {
    struct GNUNET_TIME_Relative wait_time;

    wait_time = GNUNET_TIME_absolute_get_duration (queue->start_waiting);
    LOG (GNUNET_ERROR_TYPE_DEBUG, " calling callback, time elapsed %s\n",
         GNUNET_STRINGS_relative_time_to_string (wait_time, GNUNET_NO));
    connection_destroyed = queue->cont (queue->cont_cls,
                                        queue->c, sent, queue->type, pid,
                                        queue->fwd, queue->size, wait_time);
  }
  else
  {
    connection_destroyed = GNUNET_NO;
  }

  if (NULL == peer_get_first_message (peer) && NULL != peer->core_transmit)
  {
    GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
    peer->core_transmit = NULL;
    peer->tmt_time.abs_value_us = 0;
  }

  GNUNET_free (queue);
  return connection_destroyed;
}


/**
 * @brief Queue and pass message to core when possible.
 *
 * @param peer Peer towards which to queue the message.
 * @param cls Closure (@c type dependant). It will be used by queue_send to
 *            build the message to be sent if not already prebuilt.
 * @param type Type of the message, 0 for a raw message.
 * @param size Size of the message.
 * @param c Connection this message belongs to (can be NULL).
 * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
 * @param cont Continuation to be called once CORE has taken the message.
 * @param cont_cls Closure for @c cont.
 *
 * @return Handle to cancel the message before it is sent. Once cont is called
 *         message has been sent and therefore the handle is no longer valid.
 */
struct CadetPeerQueue *
GCP_queue_add (struct CadetPeer *peer, void *cls, uint16_t type,
               uint16_t payload_type, uint32_t payload_id, size_t size,
               struct CadetConnection *c, int fwd,
               GCP_sent cont, void *cont_cls)
{
  struct CadetPeerQueue *q;
  int error_level;
  int priority;
  int call_core;

  if (NULL == c && GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN != type)
    error_level = GNUNET_ERROR_TYPE_ERROR;
  else
    error_level = GNUNET_ERROR_TYPE_INFO;
  LOG (error_level,
       "que %s (%s %4u) on connection %s (%p) %s towards %s (size %u)\n",
       GC_m2s (type), GC_m2s (payload_type), payload_id,
       GCC_2s (c), c, GC_f2s (fwd), GCP_2s (peer), size);

  if (error_level == GNUNET_ERROR_TYPE_ERROR)
    GNUNET_assert (0);
  if (NULL == peer->connections)
  {
    /* We are not connected to this peer, ignore request. */
    LOG (GNUNET_ERROR_TYPE_INFO, "%s not a neighbor\n", GCP_2s (peer));
    GNUNET_STATISTICS_update (stats, "# messages dropped due to wrong hop", 1,
                              GNUNET_NO);
    return NULL;
  }

  priority = 0;

  if (GNUNET_MESSAGE_TYPE_CADET_POLL == type ||
      GNUNET_MESSAGE_TYPE_CADET_ACK == type)
  {
    priority = 100;
  }

  LOG (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);

  call_core = (NULL == c || type == GNUNET_MESSAGE_TYPE_CADET_KX) ?
               GNUNET_YES : GCC_is_sendable (c, fwd);
  q = GNUNET_new (struct CadetPeerQueue);
  q->cls = cls;
  q->type = type;
  q->payload_type = payload_type;
  q->payload_id = payload_id;
  q->size = size;
  q->peer = peer;
  q->c = c;
  q->fwd = fwd;
  q->cont = cont;
  q->cont_cls = cont_cls;
  if (100 > priority)
  {
    GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, q);
    peer->queue_n++;
  }
  else
  {
    GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, q);
    call_core = GNUNET_YES;
  }

  q->start_waiting = GNUNET_TIME_absolute_get ();
  if (NULL == peer->core_transmit && GNUNET_YES == call_core)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "calling core tmt rdy towards %s for %u bytes\n",
         GCP_2s (peer), size);
    peer->core_transmit =
        GNUNET_CORE_notify_transmit_ready (core_handle,
                                           GNUNET_NO, get_priority (q),
                                           GNUNET_TIME_UNIT_FOREVER_REL,
                                           GNUNET_PEER_resolve2 (peer->id),
                                           get_core_size (size),
                                           &queue_send, peer);
    peer->tmt_time = GNUNET_TIME_absolute_get ();
  }
  else if (GNUNET_NO == call_core)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "core tmt rdy towards %s not needed\n",
         GCP_2s (peer));

  }
  else
  {
    struct GNUNET_TIME_Relative elapsed;
    elapsed = GNUNET_TIME_absolute_get_duration (peer->tmt_time);
    LOG (GNUNET_ERROR_TYPE_DEBUG, "core tmt rdy towards %s already called %s\n",
         GCP_2s (peer),
         GNUNET_STRINGS_relative_time_to_string (elapsed, GNUNET_NO));

  }
  queue_debug (peer, GNUNET_ERROR_TYPE_DEBUG);
  return q;
}


/**
 * Cancel all queued messages to a peer that belong to a certain connection.
 *
 * @param peer Peer towards whom to cancel.
 * @param c Connection whose queued messages to cancel. Might be destroyed by
 *          the sent continuation call.
 */
void
GCP_queue_cancel (struct CadetPeer *peer, struct CadetConnection *c)
{
  struct CadetPeerQueue *q;
  struct CadetPeerQueue *next;
  struct CadetPeerQueue *prev;
  int connection_destroyed;

  connection_destroyed = GNUNET_NO;
  for (q = peer->queue_head; NULL != q; q = next)
  {
    prev = q->prev;
    if (q->c == c)
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, "GMP queue cancel %s\n", GC_m2s (q->type));
      GNUNET_break (GNUNET_NO == connection_destroyed);
      if (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY == q->type)
      {
        q->c = NULL;
      }
      else
      {
        connection_destroyed = GCP_queue_destroy (q, GNUNET_YES, GNUNET_NO, 0);
      }

      /* Get next from prev, q->next might be already freed:
       * queue destroy -> callback -> GCC_destroy -> cancel_queues -> here
       */
      if (NULL == prev)
        next = peer->queue_head;
      else
        next = prev->next;
    }
    else
    {
      next = q->next;
    }
  }

  if (NULL == peer->queue_head && NULL != peer->core_transmit)
  {
    GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
    peer->core_transmit = NULL;
    peer->tmt_time.abs_value_us = 0;
  }
}


/**
 * Get the first transmittable message for a connection.
 *
 * @param peer Neighboring peer.
 * @param c Connection.
 *
 * @return First transmittable message.
 */
static struct CadetPeerQueue *
connection_get_first_message (struct CadetPeer *peer, struct CadetConnection *c)
{
  struct CadetPeerQueue *q;

  for (q = peer->queue_head; NULL != q; q = q->next)
  {
    if (q->c != c)
      continue;
    if (queue_is_sendable (q))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, "  sendable!!\n");
      return q;
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  not sendable\n");
  }

  return NULL;
}


/**
 * Get the first message for a connection and unqueue it.
 *
 * Only tunnel (or higher) level messages are unqueued. Connection specific
 * messages are silently destroyed upon encounter.
 *
 * @param peer Neighboring peer.
 * @param c Connection.
 * @param destroyed[in/out] Was the connection destroyed (prev/as a result)?.
 *                          Can NOT be NULL.
 *
 * @return First message for this connection.
 */
struct GNUNET_MessageHeader *
GCP_connection_pop (struct CadetPeer *peer,
                    struct CadetConnection *c,
                    int *destroyed)
{
  struct CadetPeerQueue *q;
  struct CadetPeerQueue *next;
  struct GNUNET_MessageHeader *msg;
  int dest;

  GNUNET_assert (NULL != destroyed);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "connection_pop on connection %p\n", c);
  for (q = peer->queue_head; NULL != q; q = next)
  {
    next = q->next;
    if (q->c != c)
      continue;
    LOG (GNUNET_ERROR_TYPE_DEBUG, " - queued: %s (%s %u), cont: %p\n",
         GC_m2s (q->type), GC_m2s (q->payload_type), q->payload_id,
         q->cont);
    switch (q->type)
    {
      case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
      case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
      case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
      case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
      case GNUNET_MESSAGE_TYPE_CADET_ACK:
      case GNUNET_MESSAGE_TYPE_CADET_POLL:
        dest = GCP_queue_destroy (q, GNUNET_YES, GNUNET_NO, 0);
        if (GNUNET_YES == dest)
        {
          GNUNET_break (GNUNET_NO == *destroyed);
          *destroyed = GNUNET_YES;
        }
        continue;

      case GNUNET_MESSAGE_TYPE_CADET_KX:
      case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
      case GNUNET_MESSAGE_TYPE_CADET_AX:
      case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
        msg = (struct GNUNET_MessageHeader *) q->cls;
        dest = GCP_queue_destroy (q, GNUNET_NO, GNUNET_NO, 0);
        if (GNUNET_YES == dest)
        {
          GNUNET_break (GNUNET_NO == *destroyed);
          *destroyed = GNUNET_YES;
        }
        return msg;

      default:
        GNUNET_break (0);
        LOG (GNUNET_ERROR_TYPE_DEBUG, "Unknown message %s\n", GC_m2s (q->type));
    }
  }

  return NULL;
}

/**
 * Unlock a possibly locked queue for a connection.
 *
 * If there is a message that can be sent on this connection, call core for it.
 * Otherwise (if core transmit is already called or there is no sendable
 * message) do nothing.
 *
 * @param peer Peer who keeps the queue.
 * @param c Connection whose messages to unlock.
 */
void
GCP_queue_unlock (struct CadetPeer *peer, struct CadetConnection *c)
{
  struct CadetPeerQueue *q;
  size_t size;

  if (NULL != peer->core_transmit)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  already unlocked!\n");
    return; /* Already unlocked */
  }

  q = connection_get_first_message (peer, c);
  if (NULL == q)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  queue empty!\n");
    return; /* Nothing to transmit */
  }

  size = q->size;
  peer->core_transmit =
      GNUNET_CORE_notify_transmit_ready (core_handle,
                                         GNUNET_NO, get_priority (q),
                                         GNUNET_TIME_UNIT_FOREVER_REL,
                                         GNUNET_PEER_resolve2 (peer->id),
                                         get_core_size (size),
                                         &queue_send,
                                         peer);
  peer->tmt_time = GNUNET_TIME_absolute_get ();
}


/**
 * Initialize the peer subsystem.
 *
 * @param c Configuration.
 */
void
GCP_init (const struct GNUNET_CONFIGURATION_Handle *c)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "GCP_init\n");
  in_shutdown = GNUNET_NO;
  peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_PEERS",
                                             &max_peers))
  {
    GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
                               "CADET", "MAX_PEERS", "USING DEFAULT");
    max_peers = 1000;
  }

  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DROP_PERCENT",
                                             &drop_percent))
  {
    drop_percent = 0;
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
    LOG (GNUNET_ERROR_TYPE_WARNING, "Cadet is running with DROP enabled.\n");
    LOG (GNUNET_ERROR_TYPE_WARNING, "This is NOT a good idea!\n");
    LOG (GNUNET_ERROR_TYPE_WARNING, "Remove DROP_PERCENT from config file.\n");
    LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
  }

  core_handle = GNUNET_CORE_connect (c, /* Main configuration */
                                     NULL,      /* Closure passed to CADET functions */
                                     &core_init,        /* Call core_init once connected */
                                     &core_connect,     /* Handle connects */
                                     &core_disconnect,  /* remove peers on disconnects */
                                     NULL,      /* Don't notify about all incoming messages */
                                     GNUNET_NO, /* For header only in notification */
                                     NULL,      /* Don't notify about all outbound messages */
                                     GNUNET_NO, /* For header-only out notification */
                                     core_handlers);    /* Register these handlers */
  if (GNUNET_YES !=
      GNUNET_CONFIGURATION_get_value_yesno (c, "CADET", "DISABLE_TRY_CONNECT"))
  {
    transport_handle = GNUNET_TRANSPORT_connect (c, &my_full_id, NULL, /* cls */
                                                 /* Notify callbacks */
                                                 NULL, NULL, NULL);
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
    LOG (GNUNET_ERROR_TYPE_WARNING, "*  DISABLE TRYING CONNECT in config  *\n");
    LOG (GNUNET_ERROR_TYPE_WARNING, "*  Use this only for test purposes.  *\n");
    LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
    transport_handle = NULL;
  }



  if (NULL == core_handle)
  {
    GNUNET_break (0);
    GNUNET_SCHEDULER_shutdown ();
    return;
  }

}


/**
 * Shut down the peer subsystem.
 */
void
GCP_shutdown (void)
{
  in_shutdown = GNUNET_YES;
  GNUNET_CONTAINER_multipeermap_iterate (peers,
                                         &shutdown_peer,
                                         NULL);
  if (NULL != core_handle)
  {
    GNUNET_CORE_disconnect (core_handle);
    core_handle = NULL;
  }
  if (NULL != transport_handle)
  {
    GNUNET_TRANSPORT_disconnect (transport_handle);
    transport_handle = NULL;
  }
  GNUNET_PEER_change_rc (myid, -1);
  GNUNET_CONTAINER_multipeermap_destroy (peers);
  peers = NULL;
}


/**
 * Retrieve the CadetPeer stucture associated with the peer, create one
 * and insert it in the appropriate structures if the peer is not known yet.
 *
 * @param peer_id Full identity of the peer.
 *
 * @return Existing or newly created peer structure.
 */
struct CadetPeer *
GCP_get (const struct GNUNET_PeerIdentity *peer_id)
{
  struct CadetPeer *peer;

  peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
  if (NULL == peer)
  {
    peer = GNUNET_new (struct CadetPeer);
    if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
    {
      peer_delete_oldest ();
    }
    GNUNET_assert (GNUNET_OK ==
                   GNUNET_CONTAINER_multipeermap_put (peers,
                                                      peer_id,
                                                      peer,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
    peer->id = GNUNET_PEER_intern (peer_id);
  }
  peer->last_contact = GNUNET_TIME_absolute_get ();

  return peer;
}


/**
 * Retrieve the CadetPeer stucture associated with the peer, create one
 * and insert it in the appropriate structures if the peer is not known yet.
 *
 * @param peer Short identity of the peer.
 *
 * @return Existing or newly created peer structure.
 */
struct CadetPeer *
GCP_get_short (const GNUNET_PEER_Id peer)
{
  return GCP_get (GNUNET_PEER_resolve2 (peer));
}


/**
 * Try to connect to a peer on transport level.
 *
 * @param cls Closure (peer).
 * @param tc TaskContext.
 */
static void
try_connect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct CadetPeer *peer = cls;

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

  GNUNET_TRANSPORT_try_connect (transport_handle,
                                GNUNET_PEER_resolve2 (peer->id), NULL, NULL);
}


/**
 * Try to establish a new connection to this peer (in its tunnel).
 * If the peer doesn't have any path to it yet, try to get one.
 * If the peer already has some path, send a CREATE CONNECTION towards it.
 *
 * @param peer Peer to connect to.
 */
void
GCP_connect (struct CadetPeer *peer)
{
  struct CadetTunnel *t;
  struct CadetPeerPath *p;
  struct CadetConnection *c;
  int rerun_search;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "peer_connect towards %s\n", GCP_2s (peer));

  /* If we have a current hello, try to connect using it. */
  GCP_try_connect (peer);

  t = peer->tunnel;
  c = NULL;
  rerun_search = GNUNET_NO;

  if (NULL != peer->path_head)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  some path exists\n");
    p = peer_get_best_path (peer);
    if (NULL != p)
    {
      char *s;

      s = path_2s (p);
      LOG (GNUNET_ERROR_TYPE_DEBUG, "  path to use: %s\n", s);
      GNUNET_free (s);

      c = GCT_use_path (t, p);
      if (NULL == c)
      {
        /* This case can happen when the path includes a first hop that is
         * not yet known to be connected.
         *
         * This happens quite often during testing when running cadet
         * under valgrind: core connect notifications come very late
         * and the DHT result has already come and created a valid
         * path.  In this case, the peer->connections_{pred,succ}
         * hashmaps will be NULL and tunnel_use_path will not be able
         * to create a connection from that path.
         *
         * Re-running the DHT GET should give core time to callback.
         *
         * GCT_use_path -> GCC_new -> register_neighbors takes care of
         * updating statistics about this issue.
         */
        rerun_search = GNUNET_YES;
      }
      else
      {
        GCC_send_create (c);
        return;
      }
    }
    else
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, "  but is NULL, all paths are in use\n");
    }
  }

  if (GNUNET_YES == rerun_search)
  {
    struct GNUNET_TIME_Relative delay;

    GCP_stop_search (peer);
    delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
    peer->search_delayed = GNUNET_SCHEDULER_add_delayed (delay, &delayed_search,
                                                         peer);
    return;
  }

  if (GNUNET_NO == is_searching (peer))
    GCP_start_search (peer);
}


/**
 * Chech whether there is a direct (core level)  connection to peer.
 *
 * @param peer Peer to check.
 *
 * @return #GNUNET_YES if there is a direct connection.
 */
int
GCP_is_neighbor (const struct CadetPeer *peer)
{
  struct CadetPeerPath *path;

  if (NULL == peer->connections)
    return GNUNET_NO;

  for (path = peer->path_head; NULL != path; path = path->next)
  {
    if (3 > path->length)
      return GNUNET_YES;
  }

  /* Is not a neighbor but connections is not NULL, probably disconnecting */
  return GNUNET_NO;
}


/**
 * Create and initialize a new tunnel towards a peer, in case it has none.
 * In case the peer already has a tunnel, nothing is done.
 *
 * Does not generate any traffic, just creates the local data structures.
 *
 * @param peer Peer towards which to create the tunnel.
 */
void
GCP_add_tunnel (struct CadetPeer *peer)
{
  if (NULL != peer->tunnel)
    return;
  peer->tunnel = GCT_new (peer);
}


/**
 * Add a connection to a neighboring peer.
 *
 * Store that the peer is the first hop of the connection in one
 * direction and that on peer disconnect the connection must be
 * notified and destroyed, for it will no longer be valid.
 *
 * @param peer Peer to add connection to.
 * @param c Connection to add.
 * @param pred #GNUNET_YES if we are predecessor, #GNUNET_NO if we are successor
 */
void
GCP_add_connection (struct CadetPeer *peer,
                    struct CadetConnection *c,
                    int pred)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "adding connection %s\n",
       GCC_2s (c));
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "to peer %s\n",
       GCP_2s (peer));
  GNUNET_assert (NULL != peer->connections);
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multihashmap_put (peer->connections,
                                                    GCC_get_h (c),
                                                    c,
                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Peer %s has now %u connections.\n",
       GCP_2s (peer),
       GNUNET_CONTAINER_multihashmap_size (peer->connections));
}


/**
 * Add the path to the peer and update the path used to reach it in case this
 * is the shortest.
 *
 * @param peer Destination peer to add the path to.
 * @param path New path to add. Last peer must be the peer in arg 1.
 *             Path will be either used of freed if already known.
 * @param trusted Do we trust that this path is real?
 *
 * @return path if path was taken, pointer to existing duplicate if exists
 *         NULL on error.
 */
struct CadetPeerPath *
GCP_add_path (struct CadetPeer *peer, struct CadetPeerPath *path,
              int trusted)
{
  struct CadetPeerPath *aux;
  unsigned int l;
  unsigned int l2;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
       path->length, GCP_2s (peer));

  if (NULL == peer || NULL == path
      || path->peers[path->length - 1] != peer->id)
  {
    GNUNET_break (0);
    path_destroy (path);
    return NULL;
  }

  for (l = 1; l < path->length; l++)
  {
    if (path->peers[l] == myid)
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, " shortening path by %u\n", l);
      for (l2 = 0; l2 < path->length - l; l2++)
      {
        path->peers[l2] = path->peers[l + l2];
      }
      path->length -= l;
      l = 1;
      path->peers = GNUNET_realloc (path->peers,
                                    path->length * sizeof (GNUNET_PEER_Id));
    }
  }

  LOG (GNUNET_ERROR_TYPE_DEBUG, " final length: %u\n", path->length);

  if (2 >= path->length && GNUNET_NO == trusted)
  {
    /* Only allow CORE to tell us about direct paths */
    path_destroy (path);
    return NULL;
  }

  l = path_get_length (path);
  if (0 == l)
  {
    path_destroy (path);
    return NULL;
  }

  GNUNET_assert (peer->id == path->peers[path->length - 1]);
  for (aux = peer->path_head; aux != NULL; aux = aux->next)
  {
    l2 = path_get_length (aux);
    if (l2 > l)
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, "  added\n");
      GNUNET_CONTAINER_DLL_insert_before (peer->path_head,
                                          peer->path_tail, aux, path);
      goto finish;
    }
    else
    {
      if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG, "  already known\n");
        path_destroy (path);
        return aux;
      }
    }
  }
  GNUNET_CONTAINER_DLL_insert_tail (peer->path_head, peer->path_tail,
                                    path);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  added last\n");

finish:
  if (NULL != peer->tunnel
      && CONNECTIONS_PER_TUNNEL < GCT_count_connections (peer->tunnel))
  {
    GCP_connect (peer);
  }
  return path;
}


/**
 * Add the path to the origin peer and update the path used to reach it in case
 * this is the shortest.
 * The path is given in peer_info -> destination, therefore we turn the path
 * upside down first.
 *
 * @param peer Peer to add the path to, being the origin of the path.
 * @param path New path to add after being inversed.
 *             Path will be either used or freed.
 * @param trusted Do we trust that this path is real?
 *
 * @return path if path was taken, pointer to existing duplicate if exists
 *         NULL on error.
 */
struct CadetPeerPath *
GCP_add_path_to_origin (struct CadetPeer *peer,
                        struct CadetPeerPath *path,
                        int trusted)
{
  if (NULL == path)
    return NULL;
  path_invert (path);
  return GCP_add_path (peer, path, trusted);
}


/**
 * Adds a path to the info of all the peers in the path
 *
 * @param p Path to process.
 * @param confirmed Whether we know if the path works or not.
 */
void
GCP_add_path_to_all (const struct CadetPeerPath *p, int confirmed)
{
  unsigned int i;

  /* TODO: invert and add */
  for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
  for (i++; i < p->length; i++)
  {
    struct CadetPeer *aux;
    struct CadetPeerPath *copy;

    aux = GCP_get_short (p->peers[i]);
    copy = path_duplicate (p);
    copy->length = i + 1;
    GCP_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
  }
}


/**
 * Remove any path to the peer that has the extact same peers as the one given.
 *
 * @param peer Peer to remove the path from.
 * @param path Path to remove. Is always destroyed .
 */
void
GCP_remove_path (struct CadetPeer *peer, struct CadetPeerPath *path)
{
  struct CadetPeerPath *iter;
  struct CadetPeerPath *next;

  GNUNET_assert (myid == path->peers[0]);
  GNUNET_assert (peer->id == path->peers[path->length - 1]);

  LOG (GNUNET_ERROR_TYPE_INFO,
       "Removing path %p (%u) from %s\n",
       path,
       path->length,
       GCP_2s (peer));

  for (iter = peer->path_head; NULL != iter; iter = next)
  {
    next = iter->next;
    if (0 == path_cmp (path, iter))
    {
      GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, iter);
      if (iter != path)
        path_destroy (iter);
    }
  }
  path_destroy (path);
}


/**
 * Remove a connection from a neighboring peer.
 *
 * @param peer Peer to remove connection from.
 * @param c Connection to remove.
 */
void
GCP_remove_connection (struct CadetPeer *peer,
                       const struct CadetConnection *c)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Removing connection %s\n",
       GCC_2s (c));
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "from peer %s\n",
       GCP_2s (peer));
  if ( (NULL == peer) ||
       (NULL == peer->connections) )
    return;
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap_remove (peer->connections,
                                                       GCC_get_h (c),
                                                       c));
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Peer %s remains with %u connections.\n",
       GCP_2s (peer),
       GNUNET_CONTAINER_multihashmap_size (peer->connections));
}


/**
 * Start the DHT search for new paths towards the peer: we don't have
 * enough good connections.
 *
 * @param peer Destination peer.
 */
void
GCP_start_search (struct CadetPeer *peer)
{
  const struct GNUNET_PeerIdentity *id;
  struct CadetTunnel *t = peer->tunnel;

  if (NULL != peer->search_h)
  {
    GNUNET_break (0);
    return;
  }

  if (NULL != peer->search_delayed)
    GCP_stop_search (peer);

  id = GNUNET_PEER_resolve2 (peer->id);
  peer->search_h = GCD_search (id, &search_handler, peer);

  if (NULL == t)
  {
    /* Why would we search for a peer with no tunnel towards it? */
    GNUNET_break (0);
    return;
  }

  if (CADET_TUNNEL_NEW == GCT_get_cstate (t)
      || 0 == GCT_count_any_connections (t))
  {
    GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
  }
}


/**
 * Stop the DHT search for new paths towards the peer: we already have
 * enough good connections.
 *
 * @param peer Destination peer.
 */
void
GCP_stop_search (struct CadetPeer *peer)
{
  if (NULL != peer->search_h)
  {
    GCD_search_stop (peer->search_h);
    peer->search_h = NULL;
  }
  if (NULL != peer->search_delayed)
  {
    GNUNET_SCHEDULER_cancel (peer->search_delayed);
    peer->search_delayed = NULL;
  }
}


/**
 * Get the Full ID of a peer.
 *
 * @param peer Peer to get from.
 *
 * @return Full ID of peer.
 */
const struct GNUNET_PeerIdentity *
GCP_get_id (const struct CadetPeer *peer)
{
  return GNUNET_PEER_resolve2 (peer->id);
}


/**
 * Get the Short ID of a peer.
 *
 * @param peer Peer to get from.
 *
 * @return Short ID of peer.
 */
GNUNET_PEER_Id
GCP_get_short_id (const struct CadetPeer *peer)
{
  return peer->id;
}


/**
 * Set tunnel.
 *
 * If tunnel is NULL and there was a search active, stop it, as it's useless.
 *
 * @param peer Peer.
 * @param t Tunnel.
 */
void
GCP_set_tunnel (struct CadetPeer *peer, struct CadetTunnel *t)
{
  peer->tunnel = t;
  if (NULL == t && GNUNET_YES == is_searching (peer))
  {
    GCP_stop_search (peer);
  }
}


/**
 * Get the tunnel towards a peer.
 *
 * @param peer Peer to get from.
 *
 * @return Tunnel towards peer.
 */
struct CadetTunnel *
GCP_get_tunnel (const struct CadetPeer *peer)
{
  return peer->tunnel;
}


/**
 * Set the hello message.
 *
 * @param peer Peer whose message to set.
 * @param hello Hello message.
 */
void
GCP_set_hello (struct CadetPeer *peer, const struct GNUNET_HELLO_Message *hello)
{
  struct GNUNET_HELLO_Message *old;
  size_t size;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "set hello for %s\n", GCP_2s (peer));
  if (NULL == hello)
    return;

  old = GCP_get_hello (peer);
  if (NULL == old)
  {
    size = GNUNET_HELLO_size (hello);
    LOG (GNUNET_ERROR_TYPE_DEBUG, " new (%u bytes)\n", size);
    peer->hello = GNUNET_malloc (size);
    memcpy (peer->hello, hello, size);
  }
  else
  {
    peer->hello = GNUNET_HELLO_merge (old, hello);
    LOG (GNUNET_ERROR_TYPE_DEBUG, " merge into %p (%u bytes)\n",
         peer->hello, GNUNET_HELLO_size (hello));
    GNUNET_free (old);
  }
}


/**
 * Get the hello message.
 *
 * @param peer Peer whose message to get.
 *
 * @return Hello message.
 */
struct GNUNET_HELLO_Message *
GCP_get_hello (struct CadetPeer *peer)
{
  struct GNUNET_TIME_Absolute expiration;
  struct GNUNET_TIME_Relative remaining;

  if (NULL == peer->hello)
    return NULL;

  expiration = GNUNET_HELLO_get_last_expiration (peer->hello);
  remaining = GNUNET_TIME_absolute_get_remaining (expiration);
  if (0 == remaining.rel_value_us)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, " get - hello expired on %s\n",
         GNUNET_STRINGS_absolute_time_to_string (expiration));
    GNUNET_free (peer->hello);
    peer->hello = NULL;
  }
  return peer->hello;
}


/**
 * Try to connect to a peer on TRANSPORT level.
 *
 * @param peer Peer to whom to connect.
 */
void
GCP_try_connect (struct CadetPeer *peer)
{
  struct GNUNET_HELLO_Message *hello;
  struct GNUNET_MessageHeader *mh;

  if (NULL == transport_handle)
    return;

  hello = GCP_get_hello (peer);
  if (NULL == hello)
    return;

  mh = GNUNET_HELLO_get_header (hello);
  GNUNET_TRANSPORT_offer_hello (transport_handle, mh, try_connect, peer);
}


/**
 * Notify a peer that a link between two other peers is broken. If any path
 * used that link, eliminate it.
 *
 * @param peer Peer affected by the change.
 * @param peer1 Peer whose link is broken.
 * @param peer2 Peer whose link is broken.
 */
void
GCP_notify_broken_link (struct CadetPeer *peer,
                        struct GNUNET_PeerIdentity *peer1,
                        struct GNUNET_PeerIdentity *peer2)
{
  struct CadetPeerPath *iter;
  struct CadetPeerPath *next;
  unsigned int i;
  GNUNET_PEER_Id p1;
  GNUNET_PEER_Id p2;

  p1 = GNUNET_PEER_search (peer1);
  p2 = GNUNET_PEER_search (peer2);

  LOG (GNUNET_ERROR_TYPE_DEBUG, "Link %u-%u broken\n", p1, p2);
  if (0 == p1 || 0 == p2)
  {
    /* We don't even know them */
    return;
  }

  for (iter = peer->path_head; NULL != iter; iter = next)
  {
    next = iter->next;
    for (i = 0; i < iter->length - 1; i++)
    {
      if ((iter->peers[i] == p1 && iter->peers[i + 1] == p2)
          || (iter->peers[i] == p2 && iter->peers[i + 1] == p1))
      {
        char *s;

        s = path_2s (iter);
        LOG (GNUNET_ERROR_TYPE_DEBUG, " - invalidating %s\n", s);
        GNUNET_free (s);

        path_invalidate (iter);
      }
    }
  }
}


/**
 * Count the number of known paths toward the peer.
 *
 * @param peer Peer to get path info.
 *
 * @return Number of known paths.
 */
unsigned int
GCP_count_paths (const struct CadetPeer *peer)
{
  struct CadetPeerPath *iter;
  unsigned int i;

  for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
    i++;

  return i;
}


/**
 * Iterate all known peers.
 *
 * @param iter Iterator.
 * @param cls Closure for @c iter.
 */
void
GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter,
                 void *cls)
{
  GNUNET_CONTAINER_multipeermap_iterate (peers,
                                         iter,
                                         cls);
}


/**
 * Get the static string for a peer ID.
 *
 * @param peer Peer.
 *
 * @return Static string for it's ID.
 */
const char *
GCP_2s (const struct CadetPeer *peer)
{
  if (NULL == peer)
    return "(NULL)";
  return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
}