summaryrefslogtreecommitdiff
path: root/src/cadet/gnunet-service-cadet-new_peer.c
blob: 47f725e09c64824c7084c74711d055d0ad18022c (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
/*
     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 General Public License as published
     by the Free Software Foundation; either version 3, or (at your
     option) any later version.

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

     You should have received a copy of the GNU General Public License
     along with GNUnet; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
     Boston, MA 02110-1301, USA.
*/

/**
 * @file cadet/gnunet-service-cadet-new_peer.c
 * @brief Information we track per peer.
 * @author Bartlomiej Polot
 * @author Christian Grothoff
 *
 * TODO:
 * - implement GCP_set_hello() / do HELLO advertising properly
 * - 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 (?))
 * - optimize MQM ready scans (O(n) -> O(1))
 */
#include "platform.h"
#include "gnunet_util_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 "cadet_protocol.h"
#include "cadet_path.h"
#include "gnunet-service-cadet-new.h"
#include "gnunet-service-cadet-new_connection.h"
#include "gnunet-service-cadet-new_dht.h"
#include "gnunet-service-cadet-new_peer.h"
#include "gnunet-service-cadet-new_paths.h"
#include "gnunet-service-cadet-new_tunnels.h"

/**
 * 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)




/**
 * 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
   */
  struct GNUNET_TIME_Absolute last_contact;

  /**
   * 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;

  /**
   * 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 stop the DHT search for paths to this peer
   */
  struct GNUNET_SCHEDULER_Task *search_delayedXXX;

  /**
   * 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;

  /**
   * 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 peer Peer.
 *
 * @return Static string for it's ID.
 */
const char *
GCP_2s (const struct CadetPeer *peer)
{
  if (NULL == peer)
    return "PEER(NULL)";
  return GNUNET_i2s (&peer->pid);
}


/**
 * 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;

  cp->destroy_task = NULL;
  GNUNET_assert (NULL == cp->t);
  GNUNET_assert (NULL == cp->core_mq);
  GNUNET_assert (0 == cp->path_dll_length);
  GNUNET_assert (0 == GNUNET_CONTAINER_multishortmap_size (cp->connections));
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multipeermap_remove (peers,
                                                       &cp->pid,
                                                       cp));
  GNUNET_free_non_null (cp->path_heads);
  GNUNET_free_non_null (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);
  GNUNET_CONTAINER_heap_destroy (cp->path_heap);
  GNUNET_free_non_null (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_free (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)
{
  cp->core_mq = mq;

  for (struct GCP_MessageQueueManager *mqm = cp->mqm_head;
       NULL != mqm;
       mqm = 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);
    }
  }
}


/**
 * 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 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);
  }
  GNUNET_MQ_send (cp->core_mq,
                  mqm->env);
  mqm->env = NULL;
  cp->mqm_ready_counter--;
}


/**
 * 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;

  if (0 == cp->mqm_ready_counter)
    return; /* nothing to do */
  for (struct GCP_MessageQueueManager *mqm = cp->mqm_head;
       NULL != mqm;
       mqm = mqm->next)
  {
    if (NULL == mqm->env)
      continue;
    mqm_execute (mqm);
    return;
  }
}


/**
 * 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 != 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 (0 != GNUNET_MQ_get_length (cp->core_mq))
    return;
  mqm_execute (mqm);
}


/**
 * 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 ()
{
  GNUNET_CONTAINER_multipeermap_iterate (peers,
                                         &destroy_iterator_cb,
                                         NULL);
}


/**
 * 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 (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->path_dll_length)
    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);
}


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


/**
 * 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)
{
  GNUNET_CONTAINER_DLL_remove (cp->path_heads[off],
                               cp->path_tails[off],
                               entry);
  GNUNET_assert (0 < cp->num_paths);
  cp->num_paths--;
}


/**
 * 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
 * @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)
{
  GNUNET_CONTAINER_HeapCostType desirability;
  struct CadetPeerPath *root;
  GNUNET_CONTAINER_HeapCostType root_desirability;
  struct GNUNET_CONTAINER_HeapNode *hn;

  /* FIXME: desirability is not yet initialized; tricky! */
  desirability = GCPP_get_desirability (path);
  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) )
    return NULL;

  /* Yes, we'd like to add this path, add to our heap */
  hn = GNUNET_CONTAINER_heap_insert (cp->path_heap,
                                     (void *) cp,
                                     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)
  {
    /* Now we have way too many, drop least desirable UNLESS it is in use!
       (Note that this intentionally keeps highly desireable, 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);
    if (NULL ==
        GCPP_get_connection (root,
                             cp,
                             GCPP_get_length (root) - 1))
    {
      /* Got plenty of paths to this destination, and this is a low-quality
         one that we don't care, allow it to die. */
      GNUNET_assert (root ==
                     GNUNET_CONTAINER_heap_remove_root (cp->path_heap));
      GCPP_release (root);
    }
  }
  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)
{
  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)
{
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multishortmap_put (cp->connections,
                                                     &GCC_get_id (cc)->connection_of_tunnel,
                                                     cc,
                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
}


/**
 * 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)
{
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multishortmap_remove (cp->connections,
                                                        &GCC_get_id (cc)->connection_of_tunnel,
                                                        cc));
}


/**
 * 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;

  if (NULL != cp->destroy_task)
  {
    /* It's active, do not destory! */
    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);
}


/**
 * Retrieve the CadetPeer stucture 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));
  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 peer Peer to get path info.
 * @return Number of known paths.
 */
unsigned int
GCP_count_paths (const struct CadetPeer *peer)
{
  return peer->num_paths;
}


/**
 * Iterate over the paths to a peer.
 *
 * @param peer 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 *peer,
                   GCP_PathIterator callback,
                   void *callback_cls)
{
  unsigned int ret = 0;

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


/**
 * Iterate over the paths to @a peer where
 * @a peer is at distance @a dist from us.
 *
 * @param peer Peer to get path info.
 * @param dist desired distance of @a peer 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 *peer,
                      unsigned int dist,
                      GCP_PathIterator callback,
                      void *callback_cls)
{
  unsigned int ret = 0;

  if (dist<peer->path_dll_length)
    return 0;
  for (struct CadetPeerPathEntry *pe = peer->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 peer 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 *peer,
                int create)
{
  if (NULL == peer)
    return NULL;
  if ( (NULL != peer->t) ||
       (GNUNET_NO == create) )
    return peer->t;
  peer->t = GCT_create_tunnel (peer);
  consider_peer_activate (peer);
  return peer->t;
}


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

  consider_peer_destroy (peer);
}


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


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

  if (NULL != mqm->env)
    GNUNET_MQ_discard (mqm->env);
  if (NULL != last_env)
  {
    if (NULL != cp->core_mq)
      GNUNET_MQ_send (cp->core_mq,
                      last_env);
    else
      GNUNET_MQ_discard (last_env);
  }
  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)
{
  if (NULL == cp->core_mq)
  {
    GNUNET_MQ_discard (env);
    return;
  }
  GNUNET_MQ_send (cp->core_mq,
                  env);
}




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