aboutsummaryrefslogtreecommitdiff
path: root/src/cadet/gnunet-service-cadet_peer.c
blob: 2437a3e1b1fa4f190fdb53949446033b99ddb29e (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
/*
     This file is part of GNUnet.
     Copyright (C) 2001-2017 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_peer.c
 * @brief Information we track per peer.
 * @author Bartlomiej Polot
 * @author Christian Grothoff
 *
 * TODO:
 * - optimize stopping/restarting DHT search to situations
 *   where we actually need it (i.e. not if we have a direct connection,
 *   or if we already have plenty of good short ones, or maybe even
 *   to take a break if we have some connections and have searched a lot (?))
 */
#include "platform.h"
#include "gnunet_time_lib.h"
#include "gnunet_util_lib.h"
#include "gnunet_hello_lib.h"
#include "gnunet_signatures.h"
#include "gnunet_transport_service.h"
#include "gnunet_ats_service.h"
#include "gnunet_core_service.h"
#include "gnunet_statistics_service.h"
#include "gnunet-service-cadet_peer.h"
#include "gnunet-service-cadet.h"
#include "gnunet-service-cadet_connection.h"
#include "gnunet-service-cadet_dht.h"
#include "gnunet-service-cadet_paths.h"
#include "gnunet-service-cadet_tunnels.h"


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


/**
 * How long do we wait until tearing down an idle peer?
 */
#define IDLE_PEER_TIMEOUT GNUNET_TIME_relative_multiply ( \
    GNUNET_TIME_UNIT_MINUTES, 5)

/**
 * How long do we keep paths around if we no longer care about the peer?
 */
#define IDLE_PATH_TIMEOUT GNUNET_TIME_relative_multiply ( \
    GNUNET_TIME_UNIT_MINUTES, 2)

/**
 * Queue size when we start dropping OOO messages.
 */
#define MAX_OOO_QUEUE_SIZE  100

/**
 * Data structure used to track whom we have to notify about changes
 * to our message queue.
 */
struct GCP_MessageQueueManager
{
  /**
   * Kept in a DLL.
   */
  struct GCP_MessageQueueManager *next;

  /**
   * Kept in a DLL.
   */
  struct GCP_MessageQueueManager *prev;

  /**
   * Function to call with updated message queue object.
   */
  GCP_MessageQueueNotificationCallback cb;

  /**
   * Closure for @e cb.
   */
  void *cb_cls;

  /**
   * The peer this is for.
   */
  struct CadetPeer *cp;

  /**
   * Envelope this manager would like to transmit once it is its turn.
   */
  struct GNUNET_MQ_Envelope *env;
};


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

  /**
   * Last time we heard from this peer (currently not used!)
   */
  struct GNUNET_TIME_Absolute last_connection_create;

  /**
   * Array of DLLs of paths traversing the peer, organized by the
   * offset of the peer on the larger path.
   */
  struct CadetPeerPathEntry **path_heads;

  /**
   * Array of DLL of paths traversing the peer, organized by the
   * offset of the peer on the larger path.
   */
  struct CadetPeerPathEntry **path_tails;

  /**
   * Notifications to call when @e core_mq changes.
   */
  struct GCP_MessageQueueManager *mqm_head;

  /**
   * Notifications to call when @e core_mq changes.
   */
  struct GCP_MessageQueueManager *mqm_tail;

  /**
   * Pointer to first "ready" entry in @e mqm_head.
   */
  struct GCP_MessageQueueManager *mqm_ready_ptr;

  /**
   * MIN-heap of paths owned by this peer (they also end at this
   * peer).  Ordered by desirability.
   */
  struct GNUNET_CONTAINER_Heap *path_heap;

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

  /**
   * Task to clean up @e path_heap asynchronously.
   */
  struct GNUNET_SCHEDULER_Task *heap_cleanup_task;

  /**
   * Task to destroy this entry.
   */
  struct GNUNET_SCHEDULER_Task *destroy_task;

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

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

  /**
   * Handle for core transmissions.
   */
  struct GNUNET_MQ_Handle *core_mq;

  /**
   * Hello message of the peer.
   */
  struct GNUNET_HELLO_Message *hello;

  /**
   * Handle to us offering the HELLO to the transport.
   */
  struct GNUNET_TRANSPORT_OfferHelloHandle *hello_offer;

  /**
   * Handle to our ATS request asking ATS to suggest an address
   * to TRANSPORT for this peer (to establish a direct link).
   */
  struct GNUNET_ATS_ConnectivitySuggestHandle *connectivity_suggestion;

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

  /**
   * How many paths do we have to this peer (in all @e path_heads DLLs combined).
   */
  unsigned int num_paths;

  /**
   * Sum over all of the offsets of all of the paths in the @a path_heads DLLs.
   * Used to speed-up @GCP_get_desirability_of_path() calculation.
   */
  unsigned int off_sum;

  /**
   * Number of message queue managers of this peer that have a message in waiting.
   *
   * Used to quickly see if we need to bother scanning the @e msm_head DLL.
   * TODO: could be replaced by another DLL that would then allow us to avoid
   * the O(n)-scan of the DLL for ready entries!
   */
  unsigned int mqm_ready_counter;

  /**
   * Current length of the @e path_heads and @path_tails arrays.
   * The arrays should be grown as needed.
   */
  unsigned int path_dll_length;
};


/**
 * Get the static string for a peer ID.
 *
 * @param cp Peer.
 * @return Static string for it's ID.
 */
const char *
GCP_2s (const struct CadetPeer *cp)
{
  static char buf[5];
  char *ret;

  if ((NULL == cp) ||
      (GNUNET_YES == GNUNET_is_zero (&cp->pid.public_key)))
    return "NULL";

  ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&cp->pid.public_key);
  if (NULL == ret)
    return "NULL";

  GNUNET_strlcpy (buf,
                  ret,
                  sizeof(buf));
  GNUNET_free (ret);
  return buf;
}


/**
 * Calculate how desirable a path is for @a cp if @a cp
 * is at offset @a off.
 *
 * The 'desirability_table.c' program can be used to compute a list of
 * sample outputs for different scenarios.  Basically, we score paths
 * lower if there are many alternatives, and higher if they are
 * shorter than average, and very high if they are much shorter than
 * average and without many alternatives.
 *
 * @param cp a peer reachable via a path
 * @param off offset of @a cp in the path
 * @return score how useful a path is to reach @a cp,
 *         positive scores mean path is more desirable
 */
double
GCP_get_desirability_of_path (struct CadetPeer *cp,
                              unsigned int off)
{
  unsigned int num_alts = cp->num_paths;
  unsigned int off_sum;
  double avg_sum;
  double path_delta;
  double weight_alts;

  GNUNET_assert (num_alts >= 1);  /* 'path' should be in there! */
  GNUNET_assert (0 != cp->path_dll_length);

  /* We maintain 'off_sum' in 'peer' and thereby
     avoid the SLOW recalculation each time. Kept here
     just to document what is going on. */
#if SLOW
  off_sum = 0;
  for (unsigned int j = 0; j < cp->path_dll_length; j++)
    for (struct CadetPeerPathEntry *pe = cp->path_heads[j];
         NULL != pe;
         pe = pe->next)
      off_sum += j;
  GNUNET_assert (off_sum == cp->off_sum);
#else
  off_sum = cp->off_sum;
#endif
  avg_sum = off_sum * 1.0 / cp->path_dll_length;
  path_delta = off - avg_sum;
  /* path_delta positive: path off of peer above average (bad path for peer),
     path_delta negative: path off of peer below average (good path for peer) */
  if (path_delta <= -1.0)
    weight_alts = -num_alts / path_delta;  /* discount alternative paths */
  else if (path_delta >= 1.0)
    weight_alts = num_alts * path_delta; /* overcount alternative paths */
  else
    weight_alts = num_alts; /* count alternative paths normally */


  /* off+1: long paths are generally harder to find and thus count
     a bit more as they get longer.  However, above-average paths
     still need to count less, hence the squaring of that factor. */
  return (off + 1.0) / (weight_alts * weight_alts);
}


/**
 * This peer is no longer be needed, clean it up now.
 *
 * @param cls peer to clean up
 */
static void
destroy_peer (void *cls)
{
  struct CadetPeer *cp = cls;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Destroying state about peer %s\n",
       GCP_2s (cp));
  cp->destroy_task = NULL;
  GNUNET_assert (NULL == cp->t);
  GNUNET_assert (NULL == cp->core_mq);
  GNUNET_assert (0 == cp->num_paths);
  for (unsigned int i = 0; i < cp->path_dll_length; i++)
    GNUNET_assert (NULL == cp->path_heads[i]);
  GNUNET_assert (0 == GNUNET_CONTAINER_multishortmap_size (cp->connections));
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multipeermap_remove (peers,
                                                       &cp->pid,
                                                       cp));
  GNUNET_free (cp->path_heads);
  GNUNET_free (cp->path_tails);
  cp->path_dll_length = 0;
  if (NULL != cp->search_h)
  {
    GCD_search_stop (cp->search_h);
    cp->search_h = NULL;
  }
  /* FIXME: clean up search_delayedXXX! */

  if (NULL != cp->hello_offer)
  {
    GNUNET_TRANSPORT_offer_hello_cancel (cp->hello_offer);
    cp->hello_offer = NULL;
  }
  if (NULL != cp->connectivity_suggestion)
  {
    GNUNET_ATS_connectivity_suggest_cancel (cp->connectivity_suggestion);
    cp->connectivity_suggestion = NULL;
  }
  GNUNET_CONTAINER_multishortmap_destroy (cp->connections);
  if (NULL != cp->path_heap)
  {
    GNUNET_CONTAINER_heap_destroy (cp->path_heap);
    cp->path_heap = NULL;
  }
  if (NULL != cp->heap_cleanup_task)
  {
    GNUNET_SCHEDULER_cancel (cp->heap_cleanup_task);
    cp->heap_cleanup_task = NULL;
  }
  GNUNET_free (cp->hello);
  /* Peer should not be freed if paths exist; if there are no paths,
     there ought to be no connections, and without connections, no
     notifications. Thus we can assert that mqm_head is empty at this
     point. */
  GNUNET_assert (NULL == cp->mqm_head);
  GNUNET_assert (NULL == cp->mqm_ready_ptr);
  GNUNET_free (cp);
}


/**
 * This peer is now on more "active" duty, activate processes related to it.
 *
 * @param cp the more-active peer
 */
static void
consider_peer_activate (struct CadetPeer *cp)
{
  uint32_t strength;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Updating peer %s activation state (%u connections)%s%s\n",
       GCP_2s (cp),
       GNUNET_CONTAINER_multishortmap_size (cp->connections),
       (NULL == cp->t) ? "" : " with tunnel",
       (NULL == cp->core_mq) ? "" : " with CORE link");
  if (NULL != cp->destroy_task)
  {
    /* It's active, do not destroy! */
    GNUNET_SCHEDULER_cancel (cp->destroy_task);
    cp->destroy_task = NULL;
  }
  if ((0 == GNUNET_CONTAINER_multishortmap_size (cp->connections)) &&
      (NULL == cp->t))
  {
    /* We're just on a path or directly connected; don't bother too much */
    if (NULL != cp->connectivity_suggestion)
    {
      GNUNET_ATS_connectivity_suggest_cancel (cp->connectivity_suggestion);
      cp->connectivity_suggestion = NULL;
    }
    if (NULL != cp->search_h)
    {
      GCD_search_stop (cp->search_h);
      cp->search_h = NULL;
    }
    return;
  }
  if (NULL == cp->core_mq)
  {
    /* Lacks direct connection, try to create one by querying the DHT */
    if ((NULL == cp->search_h) &&
        (DESIRED_CONNECTIONS_PER_TUNNEL > cp->num_paths))
      cp->search_h
        = GCD_search (&cp->pid);
  }
  else
  {
    /* Have direct connection, stop DHT search if active */
    if (NULL != cp->search_h)
    {
      GCD_search_stop (cp->search_h);
      cp->search_h = NULL;
    }
  }

  /* If we have a tunnel, our urge for connections is much bigger */
  strength = (NULL != cp->t) ? 32 : 1;
  if (NULL != cp->connectivity_suggestion)
    GNUNET_ATS_connectivity_suggest_cancel (cp->connectivity_suggestion);
  cp->connectivity_suggestion
    = GNUNET_ATS_connectivity_suggest (ats_ch,
                                       &cp->pid,
                                       strength);
}


/**
 * This peer may no longer be needed, consider cleaning it up.
 *
 * @param cp peer to clean up
 */
static void
consider_peer_destroy (struct CadetPeer *cp);


/**
 * We really no longere care about a peer, stop hogging memory with paths to it.
 * Afterwards, see if there is more to be cleaned up about this peer.
 *
 * @param cls a `struct CadetPeer`.
 */
static void
drop_paths (void *cls)
{
  struct CadetPeer *cp = cls;
  struct CadetPeerPath *path;

  cp->destroy_task = NULL;
  while (NULL != (path = GNUNET_CONTAINER_heap_remove_root (cp->path_heap)))
    GCPP_release (path);
  consider_peer_destroy (cp);
}


/**
 * This peer may no longer be needed, consider cleaning it up.
 *
 * @param cp peer to clean up
 */
static void
consider_peer_destroy (struct CadetPeer *cp)
{
  struct GNUNET_TIME_Relative exp;

  if (NULL != cp->destroy_task)
  {
    GNUNET_SCHEDULER_cancel (cp->destroy_task);
    cp->destroy_task = NULL;
  }
  if (NULL != cp->t)
    return; /* still relevant! */
  if (NULL != cp->core_mq)
    return; /* still relevant! */
  if (0 != GNUNET_CONTAINER_multishortmap_size (cp->connections))
    return; /* still relevant! */
  if ((NULL != cp->path_heap) &&
      (0 < GNUNET_CONTAINER_heap_get_size (cp->path_heap)))
  {
    cp->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_PATH_TIMEOUT,
                                                     &drop_paths,
                                                     cp);
    return;
  }
  if (0 != cp->num_paths)
    return; /* still relevant! */
  if (NULL != cp->hello)
  {
    /* relevant only until HELLO expires */
    exp = GNUNET_TIME_absolute_get_remaining (GNUNET_HELLO_get_last_expiration (
                                                cp->hello));
    cp->destroy_task = GNUNET_SCHEDULER_add_delayed (exp,
                                                     &destroy_peer,
                                                     cp);
    return;
  }
  cp->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_PEER_TIMEOUT,
                                                   &destroy_peer,
                                                   cp);
}


/**
 * Set the message queue to @a mq for peer @a cp and notify watchers.
 *
 * @param cp peer to modify
 * @param mq message queue to set (can be NULL)
 */
void
GCP_set_mq (struct CadetPeer *cp,
            struct GNUNET_MQ_Handle *mq)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Message queue for peer %s is now %p\n",
       GCP_2s (cp),
       mq);
  cp->core_mq = mq;
  for (struct GCP_MessageQueueManager *mqm = cp->mqm_head, *next;
       NULL != mqm;
       mqm = next)
  {
    /* Save next pointer in case mqm gets freed by the callback */
    next = mqm->next;
    if (NULL == mq)
    {
      if (NULL != mqm->env)
      {
        GNUNET_MQ_discard (mqm->env);
        mqm->env = NULL;
        mqm->cb (mqm->cb_cls,
                 GNUNET_SYSERR);
      }
      else
      {
        mqm->cb (mqm->cb_cls,
                 GNUNET_NO);
      }
    }
    else
    {
      GNUNET_assert (NULL == mqm->env);
      mqm->cb (mqm->cb_cls,
               GNUNET_YES);
    }
  }
  if ((NULL != mq) ||
      (NULL != cp->t))
    consider_peer_activate (cp);
  else
    consider_peer_destroy (cp);

  if ((NULL != mq) &&
      (NULL != cp->t))
  {
    /* have a new, direct path to the target, notify tunnel */
    struct CadetPeerPath *path;

    path = GCPP_get_path_from_route (1,
                                     &cp->pid);
    GCT_consider_path (cp->t,
                       path,
                       0);
  }
}


/**
 * Debug function should NEVER return true in production code, useful to
 * simulate losses for testcases.
 *
 * @return #GNUNET_YES or #GNUNET_NO with the decision to drop.
 */
static int
should_I_drop (void)
{
  if (0 == drop_percent)
    return GNUNET_NO;
  if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
                                101) < drop_percent)
    return GNUNET_YES;
  return GNUNET_NO;
}


/**
 * Function called when CORE took one of the messages from
 * a message queue manager and transmitted it.
 *
 * @param cls the `struct CadetPeeer` where we made progress
 */
static void
mqm_send_done (void *cls);


/**
 * Transmit current envelope from this @a mqm.
 *
 * @param mqm mqm to transmit message for now
 */
static void
mqm_execute (struct GCP_MessageQueueManager *mqm)
{
  struct CadetPeer *cp = mqm->cp;

  /* Move ready pointer to the next entry that might be ready. */
  if ((mqm == cp->mqm_ready_ptr) &&
      (NULL != mqm->next))
    cp->mqm_ready_ptr = mqm->next;
  /* Move entry to the end of the DLL, to be fair. */
  if (mqm != cp->mqm_tail)
  {
    GNUNET_CONTAINER_DLL_remove (cp->mqm_head,
                                 cp->mqm_tail,
                                 mqm);
    GNUNET_CONTAINER_DLL_insert_tail (cp->mqm_head,
                                      cp->mqm_tail,
                                      mqm);
  }
  cp->mqm_ready_counter--;
  if (GNUNET_YES == should_I_drop ())
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "DROPPING message to peer %s from MQM %p\n",
         GCP_2s (cp),
         mqm);
    GNUNET_MQ_discard (mqm->env);
    mqm->env = NULL;
    mqm_send_done (cp);
  }
  else
  {
    {
      const struct GNUNET_MessageHeader *mh;

      mh = GNUNET_MQ_env_get_msg (mqm->env);
      switch (ntohs (mh->type))
      {
      case GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX:
        {
          const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg
            = (const struct GNUNET_CADET_TunnelKeyExchangeMessage *) mh;
          LOG (GNUNET_ERROR_TYPE_DEBUG,
               "P2P forwarding KX with ephemeral %s to %s on CID %s\n",
               GNUNET_e2s (&msg->ephemeral_key),
               GCP_2s (cp),
               GNUNET_sh2s (&msg->cid.connection_of_tunnel));
        }
        break;

      default:
        break;
      }
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Sending to peer %s from MQM %p\n",
         GCP_2s (cp),
         mqm);
    GNUNET_MQ_send (cp->core_mq,
                    mqm->env);
    mqm->env = NULL;
  }
  mqm->cb (mqm->cb_cls,
           GNUNET_YES);
}


/**
 * Find the next ready message in the queue (starting
 * the search from the `cp->mqm_ready_ptr`) and if possible
 * execute the transmission.
 *
 * @param cp peer to try to send the next ready message to
 */
static void
send_next_ready (struct CadetPeer *cp)
{
  struct GCP_MessageQueueManager *mqm;

  if (0 == cp->mqm_ready_counter)
    return;
  while ((NULL != (mqm = cp->mqm_ready_ptr)) &&
         (NULL == mqm->env))
    cp->mqm_ready_ptr = mqm->next;
  if (NULL == mqm)
    return; /* nothing to do */
  mqm_execute (mqm);
}


/**
 * Function called when CORE took one of the messages from
 * a message queue manager and transmitted it.
 *
 * @param cls the `struct CadetPeeer` where we made progress
 */
static void
mqm_send_done (void *cls)
{
  struct CadetPeer *cp = cls;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Sending to peer %s completed\n",
       GCP_2s (cp));
  send_next_ready (cp);
}


/**
 * Send the message in @a env to @a cp.
 *
 * @param mqm the message queue manager to use for transmission
 * @param env envelope with the message to send; must NOT
 *            yet have a #GNUNET_MQ_notify_sent() callback attached to it
 */
void
GCP_send (struct GCP_MessageQueueManager *mqm,
          struct GNUNET_MQ_Envelope *env)
{
  struct CadetPeer *cp = mqm->cp;

  GNUNET_assert (NULL != env);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Queueing message to peer %s in MQM %p\n",
       GCP_2s (cp),
       mqm);
  GNUNET_assert (NULL != cp->core_mq);
  GNUNET_assert (NULL == mqm->env);
  GNUNET_MQ_notify_sent (env,
                         &mqm_send_done,
                         cp);
  mqm->env = env;
  cp->mqm_ready_counter++;
  if (mqm != cp->mqm_ready_ptr)
    cp->mqm_ready_ptr = cp->mqm_head;
  if (1 == cp->mqm_ready_counter)
    cp->mqm_ready_ptr = mqm;
  if (0 != GNUNET_MQ_get_length (cp->core_mq))
    return;
  send_next_ready (cp);
}


/**
 * Function called to destroy a peer now.
 *
 * @param cls NULL
 * @param pid identity of the peer (unused)
 * @param value the `struct CadetPeer` to clean up
 * @return #GNUNET_OK (continue to iterate)
 */
static int
destroy_iterator_cb (void *cls,
                     const struct GNUNET_PeerIdentity *pid,
                     void *value)
{
  struct CadetPeer *cp = value;

  if (NULL != cp->destroy_task)
  {
    GNUNET_SCHEDULER_cancel (cp->destroy_task);
    cp->destroy_task = NULL;
  }
  destroy_peer (cp);
  return GNUNET_OK;
}


/**
 * Clean up all entries about all peers.
 * Must only be called after all tunnels, CORE-connections and
 * connections are down.
 */
void
GCP_destroy_all_peers ()
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Destroying all peers now\n");
  GNUNET_CONTAINER_multipeermap_iterate (peers,
                                         &destroy_iterator_cb,
                                         NULL);
}


/**
 * Drop all paths owned by this peer, and do not
 * allow new ones to be added: We are shutting down.
 *
 * @param cp peer to drop paths to
 */
void
GCP_drop_owned_paths (struct CadetPeer *cp)
{
  struct CadetPeerPath *path;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Destroying all paths to %s\n",
       GCP_2s (cp));
  while (NULL != (path =
                    GNUNET_CONTAINER_heap_remove_root (cp->path_heap)))
    GCPP_release (path);
  GNUNET_CONTAINER_heap_destroy (cp->path_heap);
  cp->path_heap = NULL;
}


/**
 * Add an entry to the DLL of all of the paths that this peer is on.
 *
 * @param cp peer to modify
 * @param entry an entry on a path
 * @param off offset of this peer on the path
 */
void
GCP_path_entry_add (struct CadetPeer *cp,
                    struct CadetPeerPathEntry *entry,
                    unsigned int off)
{
  GNUNET_assert (cp == GCPP_get_peer_at_offset (entry->path,
                                                off));
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Discovered that peer %s is on path %s at offset %u\n",
       GCP_2s (cp),
       GCPP_2s (entry->path),
       off);
  if (off >= cp->path_dll_length)
  {
    unsigned int len = cp->path_dll_length;

    GNUNET_array_grow (cp->path_heads,
                       len,
                       off + 4);
    GNUNET_array_grow (cp->path_tails,
                       cp->path_dll_length,
                       off + 4);
  }
  GNUNET_CONTAINER_DLL_insert (cp->path_heads[off],
                               cp->path_tails[off],
                               entry);
  cp->off_sum += off;
  cp->num_paths++;

  /* If we have a tunnel to this peer, tell the tunnel that there is a
     new path available. */
  if (NULL != cp->t)
    GCT_consider_path (cp->t,
                       entry->path,
                       off);

  if ((NULL != cp->search_h) &&
      (DESIRED_CONNECTIONS_PER_TUNNEL <= cp->num_paths))
  {
    /* Now I have enough paths, stop search */
    GCD_search_stop (cp->search_h);
    cp->search_h = NULL;
  }
  if (NULL != cp->destroy_task)
  {
    /* paths changed, this resets the destroy timeout counter
       and aborts a destroy task that may no longer be valid
       to have (as we now have more paths via this peer). */
    consider_peer_destroy (cp);
  }
}


/**
 * Remove an entry from the DLL of all of the paths that this peer is on.
 *
 * @param cp peer to modify
 * @param entry an entry on a path
 * @param off offset of this peer on the path
 */
void
GCP_path_entry_remove (struct CadetPeer *cp,
                       struct CadetPeerPathEntry *entry,
                       unsigned int off)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Removing knowledge about peer %s beging on path %s at offset %u\n",
       GCP_2s (cp),
       GCPP_2s (entry->path),
       off);
  GNUNET_CONTAINER_DLL_remove (cp->path_heads[off],
                               cp->path_tails[off],
                               entry);
  GNUNET_assert (0 < cp->num_paths);
  cp->off_sum -= off;
  cp->num_paths--;
  if ((NULL == cp->core_mq) &&
      (NULL != cp->t) &&
      (NULL == cp->search_h) &&
      (DESIRED_CONNECTIONS_PER_TUNNEL > cp->num_paths))
    cp->search_h
      = GCD_search (&cp->pid);
  if (NULL == cp->destroy_task)
  {
    /* paths changed, we might now be ready for destruction, check again */
    consider_peer_destroy (cp);
  }
}


/**
 * Prune down the number of paths to this peer, we seem to
 * have way too many.
 *
 * @param cls the `struct CadetPeer` to maintain the path heap for
 */
static void
path_heap_cleanup (void *cls)
{
  struct CadetPeer *cp = cls;
  struct CadetPeerPath *root;

  cp->heap_cleanup_task = NULL;
  while (GNUNET_CONTAINER_heap_get_size (cp->path_heap) >=
         2 * DESIRED_CONNECTIONS_PER_TUNNEL)
  {
    /* Now we have way too many, drop least desirable UNLESS it is in use!
       (Note that this intentionally keeps highly desirable, but currently
       unused paths around in the hope that we might be able to switch, even
       if the number of paths exceeds the threshold.) */
    root = GNUNET_CONTAINER_heap_peek (cp->path_heap);
    GNUNET_assert (NULL != root);
    if (NULL !=
        GCPP_get_connection (root,
                             cp,
                             GCPP_get_length (root) - 1))
      break;   /* can't fix */
    /* Got plenty of paths to this destination, and this is a low-quality
       one that we don't care about. Allow it to die. */
    GNUNET_assert (root ==
                   GNUNET_CONTAINER_heap_remove_root (cp->path_heap));
    GCPP_release (root);
  }
}


/**
 * Try adding a @a path to this @a peer.  If the peer already
 * has plenty of paths, return NULL.
 *
 * @param cp peer to which the @a path leads to
 * @param path a path looking for an owner; may not be fully initialized yet!
 * @param off offset of @a cp in @a path
 * @param force force attaching the path
 * @return NULL if this peer does not care to become a new owner,
 *         otherwise the node in the peer's path heap for the @a path.
 */
struct GNUNET_CONTAINER_HeapNode *
GCP_attach_path (struct CadetPeer *cp,
                 struct CadetPeerPath *path,
                 unsigned int off,
                 int force)
{
  GNUNET_CONTAINER_HeapCostType desirability;
  struct CadetPeerPath *root;
  GNUNET_CONTAINER_HeapCostType root_desirability;
  struct GNUNET_CONTAINER_HeapNode *hn;

  GNUNET_assert (off == GCPP_get_length (path) - 1);
  GNUNET_assert (cp == GCPP_get_peer_at_offset (path,
                                                off));
  if (NULL == cp->path_heap)
  {
    /* #GCP_drop_owned_paths() was already called, we cannot take new ones! */
    GNUNET_assert (GNUNET_NO == force);
    return NULL;
  }
  desirability = GCPP_get_desirability (path);
  if (GNUNET_NO == force)
  {
    /* FIXME: desirability is not yet initialized; tricky! */
    if (GNUNET_NO ==
        GNUNET_CONTAINER_heap_peek2 (cp->path_heap,
                                     (void **) &root,
                                     &root_desirability))
    {
      root = NULL;
      root_desirability = 0;
    }

    if ((DESIRED_CONNECTIONS_PER_TUNNEL > cp->num_paths) &&
        (desirability < root_desirability))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Decided to not attach path %s to peer %s due to undesirability\n",
           GCPP_2s (path),
           GCP_2s (cp));
      return NULL;
    }
  }

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Attaching path %s to peer %s (%s)\n",
       GCPP_2s (path),
       GCP_2s (cp),
       (GNUNET_NO == force) ? "desirable" : "forced");

  /* Yes, we'd like to add this path, add to our heap */
  hn = GNUNET_CONTAINER_heap_insert (cp->path_heap,
                                     path,
                                     desirability);

  /* Consider maybe dropping other paths because of the new one */
  if ((GNUNET_CONTAINER_heap_get_size (cp->path_heap) >=
       2 * DESIRED_CONNECTIONS_PER_TUNNEL) &&
      (NULL != cp->heap_cleanup_task))
    cp->heap_cleanup_task = GNUNET_SCHEDULER_add_now (&path_heap_cleanup,
                                                      cp);
  return hn;
}


/**
 * This peer can no longer own @a path as the path
 * has been extended and a peer further down the line
 * is now the new owner.
 *
 * @param cp old owner of the @a path
 * @param path path where the ownership is lost
 * @param hn note in @a cp's path heap that must be deleted
 */
void
GCP_detach_path (struct CadetPeer *cp,
                 struct CadetPeerPath *path,
                 struct GNUNET_CONTAINER_HeapNode *hn)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Detaching path %s from peer %s\n",
       GCPP_2s (path),
       GCP_2s (cp));
  GNUNET_assert (path ==
                 GNUNET_CONTAINER_heap_remove_node (hn));
}


/**
 * Add a @a connection to this @a cp.
 *
 * @param cp peer via which the @a connection goes
 * @param cc the connection to add
 */
void
GCP_add_connection (struct CadetPeer *cp,
                    struct CadetConnection *cc)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Adding %s to peer %s\n",
       GCC_2s (cc),
       GCP_2s (cp));
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multishortmap_put (cp->connections,
                                                     &GCC_get_id (
                                                       cc)->connection_of_tunnel,
                                                     cc,
                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  if (NULL != cp->destroy_task)
  {
    GNUNET_SCHEDULER_cancel (cp->destroy_task);
    cp->destroy_task = NULL;
  }
}


/**
 * Remove a @a connection that went via this @a cp.
 *
 * @param cp peer via which the @a connection went
 * @param cc the connection to remove
 */
void
GCP_remove_connection (struct CadetPeer *cp,
                       struct CadetConnection *cc)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Removing connection %s from peer %s\n",
       GCC_2s (cc),
       GCP_2s (cp));
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multishortmap_remove (cp->connections,
                                                        &GCC_get_id (
                                                          cc)->
                                                        connection_of_tunnel,
                                                        cc));
  consider_peer_destroy (cp);
}


/**
 * Retrieve the CadetPeer structure associated with the
 * peer. Optionally create one and insert it in the appropriate
 * structures if the peer is not known yet.
 *
 * @param peer_id Full identity of the peer.
 * @param create #GNUNET_YES if a new peer should be created if unknown.
 *               #GNUNET_NO to return NULL if peer is unknown.
 * @return Existing or newly created peer structure.
 *         NULL if unknown and not requested @a create
 */
struct CadetPeer *
GCP_get (const struct GNUNET_PeerIdentity *peer_id,
         int create)
{
  struct CadetPeer *cp;

  cp = GNUNET_CONTAINER_multipeermap_get (peers,
                                          peer_id);
  if (NULL != cp)
    return cp;
  if (GNUNET_NO == create)
    return NULL;
  cp = GNUNET_new (struct CadetPeer);
  cp->pid = *peer_id;
  cp->connections = GNUNET_CONTAINER_multishortmap_create (32,
                                                           GNUNET_YES);
  cp->path_heap = GNUNET_CONTAINER_heap_create (
    GNUNET_CONTAINER_HEAP_ORDER_MIN);
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multipeermap_put (peers,
                                                    &cp->pid,
                                                    cp,
                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Creating peer %s\n",
       GCP_2s (cp));
  return cp;
}


/**
 * Obtain the peer identity for a `struct CadetPeer`.
 *
 * @param cp our peer handle
 * @return the peer identity
 */
const struct GNUNET_PeerIdentity *
GCP_get_id (struct CadetPeer *cp)
{
  return &cp->pid;
}


/**
 * Iterate over 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);
}


/**
 * Count the number of known paths toward the peer.
 *
 * @param cp Peer to get path info.
 * @return Number of known paths.
 */
unsigned int
GCP_count_paths (const struct CadetPeer *cp)
{
  return cp->num_paths;
}


/**
 * Iterate over the paths to a peer.
 *
 * @param cp Peer to get path info.
 * @param callback Function to call for every path.
 * @param callback_cls Closure for @a callback.
 * @return Number of iterated paths.
 */
unsigned int
GCP_iterate_paths (struct CadetPeer *cp,
                   GCP_PathIterator callback,
                   void *callback_cls)
{
  unsigned int ret = 0;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Iterating over paths to peer %s%s\n",
       GCP_2s (cp),
       (NULL == cp->core_mq) ? "" : " including direct link");
  if (NULL != cp->core_mq)
  {
    /* FIXME: this branch seems to duplicate the
       i=0 case below (direct link). Leave out!??? -CG */
    struct CadetPeerPath *path;

    path = GCPP_get_path_from_route (1,
                                     &cp->pid);
    ret++;
    if (GNUNET_NO ==
        callback (callback_cls,
                  path,
                  0))
      return ret;
  }
  for (unsigned int i = 0; i < cp->path_dll_length; i++)
  {
    for (struct CadetPeerPathEntry *pe = cp->path_heads[i];
         NULL != pe;
         pe = pe->next)
    {
      ret++;
      if (GNUNET_NO ==
          callback (callback_cls,
                    pe->path,
                    i))
        return ret;
    }
  }
  return ret;
}


/**
 * Iterate over the paths to a peer without direct link.
 *
 * @param cp Peer to get path info.
 * @param callback Function to call for every path.
 * @param callback_cls Closure for @a callback.
 * @return Number of iterated paths.
 */
unsigned int
GCP_iterate_indirect_paths (struct CadetPeer *cp,
                            GCP_PathIterator callback,
                            void *callback_cls)
{
  unsigned int ret = 0;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Iterating over paths to peer %s without direct link\n",
       GCP_2s (cp));
  for (unsigned int i = 1; i < cp->path_dll_length; i++)
  {
    for (struct CadetPeerPathEntry *pe = cp->path_heads[i];
         NULL != pe;
         pe = pe->next)
    {
      ret++;
      if (GNUNET_NO ==
          callback (callback_cls,
                    pe->path,
                    i))
        return ret;
    }
  }
  return ret;
}


/**
 * Iterate over the paths to @a cp where
 * @a cp is at distance @a dist from us.
 *
 * @param cp Peer to get path info.
 * @param dist desired distance of @a cp to us on the path
 * @param callback Function to call for every path.
 * @param callback_cls Closure for @a callback.
 * @return Number of iterated paths.
 */
unsigned int
GCP_iterate_paths_at (struct CadetPeer *cp,
                      unsigned int dist,
                      GCP_PathIterator callback,
                      void *callback_cls)
{
  unsigned int ret = 0;

  if (dist >= cp->path_dll_length)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Asked to look for paths at distance %u, but maximum for me is < %u\n",
         dist,
         cp->path_dll_length);
    return 0;
  }
  for (struct CadetPeerPathEntry *pe = cp->path_heads[dist];
       NULL != pe;
       pe = pe->next)
  {
    if (GNUNET_NO ==
        callback (callback_cls,
                  pe->path,
                  dist))
      return ret;
    ret++;
  }
  return ret;
}


/**
 * Get the tunnel towards a peer.
 *
 * @param cp Peer to get from.
 * @param create #GNUNET_YES to create a tunnel if we do not have one
 * @return Tunnel towards peer.
 */
struct CadetTunnel *
GCP_get_tunnel (struct CadetPeer *cp,
                int create)
{
  if (NULL == cp)
    return NULL;
  if ((NULL != cp->t) ||
      (GNUNET_NO == create))
    return cp->t;
  cp->t = GCT_create_tunnel (cp);
  consider_peer_activate (cp);
  return cp->t;
}


/**
 * Hello offer was passed to the transport service. Mark it
 * as done.
 *
 * @param cls the `struct CadetPeer` where the offer completed
 */
static void
hello_offer_done (void *cls)
{
  struct CadetPeer *cp = cls;

  cp->hello_offer = NULL;
}


/**
 * We got a HELLO for a @a peer, remember it, and possibly
 * trigger adequate actions (like trying to connect).
 *
 * @param cp the peer we got a HELLO for
 * @param hello the HELLO to remember
 */
void
GCP_set_hello (struct CadetPeer *cp,
               const struct GNUNET_HELLO_Message *hello)
{
  struct GNUNET_HELLO_Message *mrg;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Got %u byte HELLO for peer %s\n",
       (unsigned int) GNUNET_HELLO_size (hello),
       GCP_2s (cp));
  if (NULL != cp->hello_offer)
  {
    GNUNET_TRANSPORT_offer_hello_cancel (cp->hello_offer);
    cp->hello_offer = NULL;
  }
  if (NULL != cp->hello)
  {
    mrg = GNUNET_HELLO_merge (hello,
                              cp->hello);
    GNUNET_free (cp->hello);
    cp->hello = mrg;
  }
  else
  {
    cp->hello = GNUNET_memdup (hello,
                               GNUNET_HELLO_size (hello));
  }
  cp->hello_offer
    = GNUNET_TRANSPORT_offer_hello (cfg,
                                    GNUNET_HELLO_get_header (cp->hello),
                                    &hello_offer_done,
                                    cp);
  /* New HELLO means cp's destruction time may change... */
  consider_peer_destroy (cp);
}


/**
 * The tunnel to the given peer no longer exists, remove it from our
 * data structures, and possibly clean up the peer itself.
 *
 * @param cp the peer affected
 * @param t the dead tunnel
 */
void
GCP_drop_tunnel (struct CadetPeer *cp,
                 struct CadetTunnel *t)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Dropping tunnel %s to peer %s\n",
       GCT_2s (t),
       GCP_2s (cp));
  GNUNET_assert (cp->t == t);
  cp->t = NULL;
  consider_peer_destroy (cp);
}


/**
 * Test if @a cp has a core-level connection
 *
 * @param cp peer to test
 * @return #GNUNET_YES if @a cp has a core-level connection
 */
int
GCP_has_core_connection (struct CadetPeer *cp)
{
  return (NULL != cp->core_mq) ? GNUNET_YES : GNUNET_NO;
}


/**
 * Start message queue change notifications.
 *
 * @param cp peer to notify for
 * @param cb function to call if mq becomes available or unavailable
 * @param cb_cls closure for @a cb
 * @return handle to cancel request
 */
struct GCP_MessageQueueManager *
GCP_request_mq (struct CadetPeer *cp,
                GCP_MessageQueueNotificationCallback cb,
                void *cb_cls)
{
  struct GCP_MessageQueueManager *mqm;

  mqm = GNUNET_new (struct GCP_MessageQueueManager);
  mqm->cb = cb;
  mqm->cb_cls = cb_cls;
  mqm->cp = cp;
  GNUNET_CONTAINER_DLL_insert (cp->mqm_head,
                               cp->mqm_tail,
                               mqm);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Creating MQM %p for peer %s\n",
       mqm,
       GCP_2s (cp));
  if (NULL != cp->core_mq)
    cb (cb_cls,
        GNUNET_YES);
  return mqm;
}


/**
 * Stops message queue change notifications.
 *
 * @param mqm handle matching request to cancel
 * @param last_env final message to transmit, or NULL
 */
void
GCP_request_mq_cancel (struct GCP_MessageQueueManager *mqm,
                       struct GNUNET_MQ_Envelope *last_env)
{
  struct CadetPeer *cp = mqm->cp;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Destroying MQM %p for peer %s%s\n",
       mqm,
       GCP_2s (cp),
       (NULL == last_env) ? "" : " with last ditch transmission");
  if (NULL != mqm->env)
    GNUNET_MQ_discard (mqm->env);
  if (NULL != last_env)
  {
    if (NULL != cp->core_mq)
    {
      GNUNET_MQ_notify_sent (last_env,
                             &mqm_send_done,
                             cp);
      GNUNET_MQ_send (cp->core_mq,
                      last_env);
    }
    else
    {
      GNUNET_MQ_discard (last_env);
    }
  }
  if (cp->mqm_ready_ptr == mqm)
    cp->mqm_ready_ptr = mqm->next;
  GNUNET_CONTAINER_DLL_remove (cp->mqm_head,
                               cp->mqm_tail,
                               mqm);
  GNUNET_free (mqm);
}


/**
 * Send the message in @a env to @a cp, overriding queueing logic.
 * This function should only be used to send error messages outside
 * of flow and congestion control, similar to ICMP.  Note that
 * the envelope may be silently discarded as well.
 *
 * @param cp peer to send the message to
 * @param env envelope with the message to send
 */
void
GCP_send_ooo (struct CadetPeer *cp,
              struct GNUNET_MQ_Envelope *env)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Sending message to %s out of management\n",
       GCP_2s (cp));
  if (NULL == cp->core_mq)
  {
    GNUNET_MQ_discard (env);
    return;
  }
  if (GNUNET_MQ_get_length (cp->core_mq) > MAX_OOO_QUEUE_SIZE)
  {
    GNUNET_MQ_discard (env);
    return;
  }
  GNUNET_MQ_notify_sent (env,
                         &mqm_send_done,
                         cp);
  GNUNET_MQ_send (cp->core_mq,
                  env);
}


/**
 * Checking if a monotime value is newer than the last monotime value received from a peer. If the time value is newer it will be stored at the peer.
 *
 * @param peer The peer we received a new time value from.
 * @param monotime Time value we check against the last time value we received from a peer.
 * @return GNUNET_YES if monotime is newer than the last received time value, GNUNET_NO if monotime is not newer.
 */
int
GCP_check_and_update_monotime (struct CadetPeer *peer,
                               struct GNUNET_TIME_AbsoluteNBO monotime)
{

  struct GNUNET_TIME_Absolute mt = GNUNET_TIME_absolute_ntoh (monotime);

  if (mt.abs_value_us > *(&peer->last_connection_create.abs_value_us))
  {
    peer->last_connection_create = mt;
    return GNUNET_YES;
  }
  return GNUNET_NO;
}


/**
 * Checking the signature for a monotime of a GNUNET_CADET_ConnectionCreateMessage.
 *
 * @param peer The peer that signed the monotime value.
 * @param msg The GNUNET_CADET_ConnectionCreateMessage with the monotime value.
 * @return GNUNET_OK if the signature is good, GNUNET_SYSERR if not.
 */
int
GCP_check_monotime_sig (struct CadetPeer *peer,
                        const struct GNUNET_CADET_ConnectionCreateMessage *msg)
{
  struct CadetConnectionCreatePS cp = { .purpose.purpose = htonl (
                                          GNUNET_SIGNATURE_PURPOSE_CADET_CONNECTION_INITIATOR),
                                        .purpose.size = htonl (sizeof(cp)),
                                        .monotonic_time = msg->monotime};

  if (GNUNET_OK !=
      GNUNET_CRYPTO_eddsa_verify (
        GNUNET_SIGNATURE_PURPOSE_CADET_CONNECTION_INITIATOR,
        &cp,
        &msg->monotime_sig,
        &peer->pid.public_key))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/* end of gnunet-service-cadet-new_peer.c */