fix shutdown logic
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_peer.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2001-2017 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file cadet/gnunet-service-cadet-new_peer.c
23  * @brief Information we track per peer.
24  * @author Bartlomiej Polot
25  * @author Christian Grothoff
26  *
27  * TODO:
28  * - optimize stopping/restarting DHT search to situations
29  *   where we actually need it (i.e. not if we have a direct connection,
30  *   or if we already have plenty of good short ones, or maybe even
31  *   to take a break if we have some connections and have searched a lot (?))
32  * - optimize MQM ready scans (O(n) -> O(1))
33  */
34 #include "platform.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_hello_lib.h"
37 #include "gnunet_signatures.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_ats_service.h"
40 #include "gnunet_core_service.h"
41 #include "gnunet_statistics_service.h"
42 #include "cadet_protocol.h"
43 #include "gnunet-service-cadet-new.h"
44 #include "gnunet-service-cadet-new_connection.h"
45 #include "gnunet-service-cadet-new_dht.h"
46 #include "gnunet-service-cadet-new_peer.h"
47 #include "gnunet-service-cadet-new_paths.h"
48 #include "gnunet-service-cadet-new_tunnels.h"
49
50
51 #define LOG(level, ...) GNUNET_log_from(level,"cadet-per",__VA_ARGS__)
52
53
54 /**
55  * How long do we wait until tearing down an idle peer?
56  */
57 #define IDLE_PEER_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
58
59 /**
60  * How long do we keep paths around if we no longer care about the peer?
61  */
62 #define IDLE_PATH_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
63
64
65
66
67 /**
68  * Data structure used to track whom we have to notify about changes
69  * to our message queue.
70  */
71 struct GCP_MessageQueueManager
72 {
73
74   /**
75    * Kept in a DLL.
76    */
77   struct GCP_MessageQueueManager *next;
78
79   /**
80    * Kept in a DLL.
81    */
82   struct GCP_MessageQueueManager *prev;
83
84   /**
85    * Function to call with updated message queue object.
86    */
87   GCP_MessageQueueNotificationCallback cb;
88
89   /**
90    * Closure for @e cb.
91    */
92   void *cb_cls;
93
94   /**
95    * The peer this is for.
96    */
97   struct CadetPeer *cp;
98
99   /**
100    * Envelope this manager would like to transmit once it is its turn.
101    */
102   struct GNUNET_MQ_Envelope *env;
103
104 };
105
106
107 /**
108  * Struct containing all information regarding a given peer
109  */
110 struct CadetPeer
111 {
112   /**
113    * ID of the peer
114    */
115   struct GNUNET_PeerIdentity pid;
116
117   /**
118    * Last time we heard from this peer
119    */
120   struct GNUNET_TIME_Absolute last_contact;
121
122   /**
123    * Array of DLLs of paths traversing the peer, organized by the
124    * offset of the peer on the larger path.
125    */
126   struct CadetPeerPathEntry **path_heads;
127
128   /**
129    * Array of DLL of paths traversing the peer, organized by the
130    * offset of the peer on the larger path.
131    */
132   struct CadetPeerPathEntry **path_tails;
133
134   /**
135    * Notifications to call when @e core_mq changes.
136    */
137   struct GCP_MessageQueueManager *mqm_head;
138
139   /**
140    * Notifications to call when @e core_mq changes.
141    */
142   struct GCP_MessageQueueManager *mqm_tail;
143
144   /**
145    * MIN-heap of paths owned by this peer (they also end at this
146    * peer).  Ordered by desirability.
147    */
148   struct GNUNET_CONTAINER_Heap *path_heap;
149
150   /**
151    * Handle to stop the DHT search for paths to this peer
152    */
153   struct GCD_search_handle *search_h;
154
155   /**
156    * Task to stop the DHT search for paths to this peer
157    */
158   struct GNUNET_SCHEDULER_Task *search_delayedXXX;
159
160   /**
161    * Task to destroy this entry.
162    */
163   struct GNUNET_SCHEDULER_Task *destroy_task;
164
165   /**
166    * Tunnel to this peer, if any.
167    */
168   struct CadetTunnel *t;
169
170   /**
171    * Connections that go through this peer; indexed by tid.
172    */
173   struct GNUNET_CONTAINER_MultiShortmap *connections;
174
175   /**
176    * Handle for core transmissions.
177    */
178   struct GNUNET_MQ_Handle *core_mq;
179
180   /**
181    * Hello message of the peer.
182    */
183   struct GNUNET_HELLO_Message *hello;
184
185   /**
186    * Handle to us offering the HELLO to the transport.
187    */
188   struct GNUNET_TRANSPORT_OfferHelloHandle *hello_offer;
189
190   /**
191    * Handle to our ATS request asking ATS to suggest an address
192    * to TRANSPORT for this peer (to establish a direct link).
193    */
194   struct GNUNET_ATS_ConnectivitySuggestHandle *connectivity_suggestion;
195
196   /**
197    * How many messages are in the queue to this peer.
198    */
199   unsigned int queue_n;
200
201   /**
202    * How many paths do we have to this peer (in all @e path_heads DLLs combined).
203    */
204   unsigned int num_paths;
205
206   /**
207    * Number of message queue managers of this peer that have a message in waiting.
208    *
209    * Used to quickly see if we need to bother scanning the @e msm_head DLL.
210    * TODO: could be replaced by another DLL that would then allow us to avoid
211    * the O(n)-scan of the DLL for ready entries!
212    */
213   unsigned int mqm_ready_counter;
214
215   /**
216    * Current length of the @e path_heads and @path_tails arrays.
217    * The arrays should be grown as needed.
218    */
219   unsigned int path_dll_length;
220
221 };
222
223
224 /**
225  * Get the static string for a peer ID.
226  *
227  * @param cp Peer.
228  * @return Static string for it's ID.
229  */
230 const char *
231 GCP_2s (const struct CadetPeer *cp)
232 {
233   static char buf[32];
234
235   GNUNET_snprintf (buf,
236                    sizeof (buf),
237                    "P(%s)",
238                    GNUNET_i2s (&cp->pid));
239   return buf;
240 }
241
242
243 /**
244  * This peer is no longer be needed, clean it up now.
245  *
246  * @param cls peer to clean up
247  */
248 static void
249 destroy_peer (void *cls)
250 {
251   struct CadetPeer *cp = cls;
252
253   LOG (GNUNET_ERROR_TYPE_DEBUG,
254        "Destroying state about peer %s\n",
255        GCP_2s (cp));
256   cp->destroy_task = NULL;
257   GNUNET_assert (NULL == cp->t);
258   GNUNET_assert (NULL == cp->core_mq);
259   for (unsigned int i=0;i<cp->path_dll_length;i++)
260     GNUNET_assert (NULL == cp->path_heads[i]);
261   GNUNET_assert (0 == GNUNET_CONTAINER_multishortmap_size (cp->connections));
262   GNUNET_assert (GNUNET_YES ==
263                  GNUNET_CONTAINER_multipeermap_remove (peers,
264                                                        &cp->pid,
265                                                        cp));
266   GNUNET_free_non_null (cp->path_heads);
267   GNUNET_free_non_null (cp->path_tails);
268   cp->path_dll_length = 0;
269   if (NULL != cp->search_h)
270   {
271     GCD_search_stop (cp->search_h);
272     cp->search_h = NULL;
273   }
274   /* FIXME: clean up search_delayedXXX! */
275
276   if (NULL != cp->hello_offer)
277   {
278     GNUNET_TRANSPORT_offer_hello_cancel (cp->hello_offer);
279     cp->hello_offer = NULL;
280   }
281   if (NULL != cp->connectivity_suggestion)
282   {
283     GNUNET_ATS_connectivity_suggest_cancel (cp->connectivity_suggestion);
284     cp->connectivity_suggestion = NULL;
285   }
286   GNUNET_CONTAINER_multishortmap_destroy (cp->connections);
287   if (NULL != cp->path_heap)
288   {
289     GNUNET_CONTAINER_heap_destroy (cp->path_heap);
290     cp->path_heap = NULL;
291   }
292   GNUNET_free_non_null (cp->hello);
293   /* Peer should not be freed if paths exist; if there are no paths,
294      there ought to be no connections, and without connections, no
295      notifications. Thus we can assert that mqm_head is empty at this
296      point. */
297   GNUNET_assert (NULL == cp->mqm_head);
298   GNUNET_free (cp);
299 }
300
301
302 /**
303  * This peer is now on more "active" duty, activate processes related to it.
304  *
305  * @param cp the more-active peer
306  */
307 static void
308 consider_peer_activate (struct CadetPeer *cp)
309 {
310   uint32_t strength;
311
312   LOG (GNUNET_ERROR_TYPE_DEBUG,
313        "Updating peer %s activation state (%u connections)%s%s\n",
314        GCP_2s (cp),
315        GNUNET_CONTAINER_multishortmap_size (cp->connections),
316        (NULL == cp->t) ? "" : " with tunnel",
317        (NULL == cp->core_mq) ? "" : " with CORE link");
318   if (NULL != cp->destroy_task)
319   {
320     /* It's active, do not destory! */
321     GNUNET_SCHEDULER_cancel (cp->destroy_task);
322     cp->destroy_task = NULL;
323   }
324   if ( (0 == GNUNET_CONTAINER_multishortmap_size (cp->connections)) &&
325        (NULL == cp->t) )
326   {
327     /* We're just on a path or directly connected; don't bother too much */
328     if (NULL != cp->connectivity_suggestion)
329     {
330       GNUNET_ATS_connectivity_suggest_cancel (cp->connectivity_suggestion);
331       cp->connectivity_suggestion = NULL;
332     }
333     if (NULL != cp->search_h)
334     {
335       GCD_search_stop (cp->search_h);
336       cp->search_h = NULL;
337     }
338     return;
339   }
340   if (NULL == cp->core_mq)
341   {
342     /* Lacks direct connection, try to create one by querying the DHT */
343     if ( (NULL == cp->search_h) &&
344          (DESIRED_CONNECTIONS_PER_TUNNEL > cp->num_paths) )
345       cp->search_h
346         = GCD_search (&cp->pid);
347   }
348   else
349   {
350     /* Have direct connection, stop DHT search if active */
351     if (NULL != cp->search_h)
352     {
353       GCD_search_stop (cp->search_h);
354       cp->search_h = NULL;
355     }
356   }
357
358   /* If we have a tunnel, our urge for connections is much bigger */
359   strength = (NULL != cp->t) ? 32 : 1;
360   if (NULL != cp->connectivity_suggestion)
361     GNUNET_ATS_connectivity_suggest_cancel (cp->connectivity_suggestion);
362   cp->connectivity_suggestion
363     = GNUNET_ATS_connectivity_suggest (ats_ch,
364                                        &cp->pid,
365                                        strength);
366 }
367
368
369 /**
370  * This peer may no longer be needed, consider cleaning it up.
371  *
372  * @param cp peer to clean up
373  */
374 static void
375 consider_peer_destroy (struct CadetPeer *cp);
376
377
378 /**
379  * We really no longere care about a peer, stop hogging memory with paths to it.
380  * Afterwards, see if there is more to be cleaned up about this peer.
381  *
382  * @param cls a `struct CadetPeer`.
383  */
384 static void
385 drop_paths (void *cls)
386 {
387   struct CadetPeer *cp = cls;
388   struct CadetPeerPath *path;
389
390   cp->destroy_task = NULL;
391   while (NULL != (path = GNUNET_CONTAINER_heap_remove_root (cp->path_heap)))
392     GCPP_release (path);
393   consider_peer_destroy (cp);
394 }
395
396
397 /**
398  * This peer may no longer be needed, consider cleaning it up.
399  *
400  * @param cp peer to clean up
401  */
402 static void
403 consider_peer_destroy (struct CadetPeer *cp)
404 {
405   struct GNUNET_TIME_Relative exp;
406
407   if (NULL != cp->destroy_task)
408   {
409     GNUNET_SCHEDULER_cancel (cp->destroy_task);
410     cp->destroy_task = NULL;
411   }
412   if (NULL != cp->t)
413     return; /* still relevant! */
414   if (NULL != cp->core_mq)
415     return; /* still relevant! */
416   if (0 != GNUNET_CONTAINER_multishortmap_size (cp->connections))
417     return; /* still relevant! */
418   if (0 < GNUNET_CONTAINER_heap_get_size (cp->path_heap))
419   {
420     cp->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_PATH_TIMEOUT,
421                                                      &drop_paths,
422                                                      cp);
423     return;
424   }
425   for (unsigned int i=0;i<cp->path_dll_length;i++)
426     if (NULL != cp->path_heads[i])
427       return; /* still relevant! */
428   if (NULL != cp->hello)
429   {
430     /* relevant only until HELLO expires */
431     exp = GNUNET_TIME_absolute_get_remaining (GNUNET_HELLO_get_last_expiration (cp->hello));
432     cp->destroy_task = GNUNET_SCHEDULER_add_delayed (exp,
433                                                      &destroy_peer,
434                                                      cp);
435     return;
436   }
437   cp->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_PEER_TIMEOUT,
438                                                    &destroy_peer,
439                                                    cp);
440 }
441
442
443 /**
444  * Set the message queue to @a mq for peer @a cp and notify watchers.
445  *
446  * @param cp peer to modify
447  * @param mq message queue to set (can be NULL)
448  */
449 void
450 GCP_set_mq (struct CadetPeer *cp,
451             struct GNUNET_MQ_Handle *mq)
452 {
453   LOG (GNUNET_ERROR_TYPE_DEBUG,
454        "Message queue for peer %s is now %p\n",
455        GCP_2s (cp),
456        mq);
457   cp->core_mq = mq;
458   for (struct GCP_MessageQueueManager *mqm = cp->mqm_head;
459        NULL != mqm;
460        mqm = mqm->next)
461   {
462     if (NULL == mq)
463     {
464       if (NULL != mqm->env)
465       {
466         GNUNET_MQ_discard (mqm->env);
467         mqm->env = NULL;
468         mqm->cb (mqm->cb_cls,
469                  GNUNET_SYSERR);
470       }
471       else
472       {
473         mqm->cb (mqm->cb_cls,
474                  GNUNET_NO);
475       }
476     }
477     else
478     {
479       GNUNET_assert (NULL == mqm->env);
480       mqm->cb (mqm->cb_cls,
481                GNUNET_YES);
482     }
483   }
484   if ( (NULL != mq) ||
485        (NULL != cp->t) )
486     consider_peer_activate (cp);
487   else
488     consider_peer_destroy (cp);
489
490   if ( (NULL != mq) &&
491        (NULL != cp->t) )
492   {
493     /* have a new, direct path to the target, notify tunnel */
494     struct CadetPeerPath *path;
495
496     path = GCPP_get_path_from_route (1,
497                                      &cp->pid);
498     GCT_consider_path (cp->t,
499                        path,
500                        0);
501   }
502 }
503
504
505 /**
506  * Transmit current envelope from this @a mqm.
507  *
508  * @param mqm mqm to transmit message for now
509  */
510 static void
511 mqm_execute (struct GCP_MessageQueueManager *mqm)
512 {
513   struct CadetPeer *cp = mqm->cp;
514
515   LOG (GNUNET_ERROR_TYPE_DEBUG,
516        "Sending to peer %s from MQM %p\n",
517        GCP_2s (cp),
518        mqm);
519   /* Move entry to the end of the DLL, to be fair. */
520   if (mqm != cp->mqm_tail)
521   {
522     GNUNET_CONTAINER_DLL_remove (cp->mqm_head,
523                                  cp->mqm_tail,
524                                  mqm);
525     GNUNET_CONTAINER_DLL_insert_tail (cp->mqm_head,
526                                       cp->mqm_tail,
527                                       mqm);
528   }
529   GNUNET_MQ_send (cp->core_mq,
530                   mqm->env);
531   mqm->env = NULL;
532   cp->mqm_ready_counter--;
533 }
534
535
536 /**
537  * Function called when CORE took one of the messages from
538  * a message queue manager and transmitted it.
539  *
540  * @param cls the `struct CadetPeeer` where we made progress
541  */
542 static void
543 mqm_send_done (void *cls)
544 {
545   struct CadetPeer *cp = cls;
546
547   LOG (GNUNET_ERROR_TYPE_DEBUG,
548        "Sending to peer %s completed\n",
549        GCP_2s (cp));
550   if (0 == cp->mqm_ready_counter)
551     return; /* nothing to do */
552   for (struct GCP_MessageQueueManager *mqm = cp->mqm_head;
553        NULL != mqm;
554        mqm = mqm->next)
555   {
556     if (NULL == mqm->env)
557       continue;
558     mqm_execute (mqm);
559     return;
560   }
561 }
562
563
564 /**
565  * Send the message in @a env to @a cp.
566  *
567  * @param mqm the message queue manager to use for transmission
568  * @param env envelope with the message to send; must NOT
569  *            yet have a #GNUNET_MQ_notify_sent() callback attached to it
570  */
571 void
572 GCP_send (struct GCP_MessageQueueManager *mqm,
573           struct GNUNET_MQ_Envelope *env)
574 {
575   struct CadetPeer *cp = mqm->cp;
576
577   LOG (GNUNET_ERROR_TYPE_DEBUG,
578        "Queueing message to peer %s in MQM %p\n",
579        GCP_2s (cp),
580        mqm);
581   GNUNET_assert (NULL != cp->core_mq);
582   GNUNET_assert (NULL == mqm->env);
583   GNUNET_MQ_notify_sent (env,
584                          &mqm_send_done,
585                          cp);
586   mqm->env = env;
587   cp->mqm_ready_counter++;
588   if (0 != GNUNET_MQ_get_length (cp->core_mq))
589     return;
590   mqm_execute (mqm);
591 }
592
593
594 /**
595  * Function called to destroy a peer now.
596  *
597  * @param cls NULL
598  * @param pid identity of the peer (unused)
599  * @param value the `struct CadetPeer` to clean up
600  * @return #GNUNET_OK (continue to iterate)
601  */
602 static int
603 destroy_iterator_cb (void *cls,
604                      const struct GNUNET_PeerIdentity *pid,
605                      void *value)
606 {
607   struct CadetPeer *cp = value;
608
609   if (NULL != cp->destroy_task)
610   {
611     GNUNET_SCHEDULER_cancel (cp->destroy_task);
612     cp->destroy_task = NULL;
613   }
614   destroy_peer (cp);
615   return GNUNET_OK;
616 }
617
618
619 /**
620  * Clean up all entries about all peers.
621  * Must only be called after all tunnels, CORE-connections and
622  * connections are down.
623  */
624 void
625 GCP_destroy_all_peers ()
626 {
627   LOG (GNUNET_ERROR_TYPE_DEBUG,
628        "Destroying all peers now\n");
629   GNUNET_CONTAINER_multipeermap_iterate (peers,
630                                          &destroy_iterator_cb,
631                                          NULL);
632 }
633
634
635 /**
636  * Drop all paths owned by this peer, and do not
637  * allow new ones to be added: We are shutting down.
638  *
639  * @param cp peer to drop paths to
640  */
641 void
642 GCP_drop_owned_paths (struct CadetPeer *cp)
643 {
644   struct CadetPeerPath *path;
645
646   LOG (GNUNET_ERROR_TYPE_DEBUG,
647        "Destroying all paths to %s\n",
648        GCP_2s (cp));
649   while (NULL != (path =
650                   GNUNET_CONTAINER_heap_remove_root (cp->path_heap)))
651     GCPP_release (path);
652   GNUNET_CONTAINER_heap_destroy (cp->path_heap);
653   cp->path_heap = NULL;
654 }
655
656
657 /**
658  * Add an entry to the DLL of all of the paths that this peer is on.
659  *
660  * @param cp peer to modify
661  * @param entry an entry on a path
662  * @param off offset of this peer on the path
663  */
664 void
665 GCP_path_entry_add (struct CadetPeer *cp,
666                     struct CadetPeerPathEntry *entry,
667                     unsigned int off)
668 {
669   LOG (GNUNET_ERROR_TYPE_DEBUG,
670        "Discovered that peer %s is on path %s at offset %u\n",
671        GCP_2s (cp),
672        GCPP_2s (entry->path),
673        off);
674   if (off >= cp->path_dll_length)
675   {
676     unsigned int len = cp->path_dll_length;
677
678     GNUNET_array_grow (cp->path_heads,
679                        len,
680                        off + 4);
681     GNUNET_array_grow (cp->path_tails,
682                        cp->path_dll_length,
683                        off + 4);
684   }
685   GNUNET_CONTAINER_DLL_insert (cp->path_heads[off],
686                                cp->path_tails[off],
687                                entry);
688   cp->num_paths++;
689
690   /* If we have a tunnel to this peer, tell the tunnel that there is a
691      new path available. */
692   if (NULL != cp->t)
693     GCT_consider_path (cp->t,
694                        entry->path,
695                        off);
696
697   if ( (NULL != cp->search_h) &&
698        (DESIRED_CONNECTIONS_PER_TUNNEL <= cp->num_paths) )
699   {
700     /* Now I have enough paths, stop search */
701     GCD_search_stop (cp->search_h);
702     cp->search_h = NULL;
703   }
704 }
705
706
707 /**
708  * Remove an entry from the DLL of all of the paths that this peer is on.
709  *
710  * @param cp peer to modify
711  * @param entry an entry on a path
712  * @param off offset of this peer on the path
713  */
714 void
715 GCP_path_entry_remove (struct CadetPeer *cp,
716                        struct CadetPeerPathEntry *entry,
717                        unsigned int off)
718 {
719   LOG (GNUNET_ERROR_TYPE_DEBUG,
720        "Removing knowledge about peer %s beging on path %s at offset %u\n",
721        GCP_2s (cp),
722        GCPP_2s (entry->path),
723        off);
724   GNUNET_CONTAINER_DLL_remove (cp->path_heads[off],
725                                cp->path_tails[off],
726                                entry);
727   GNUNET_assert (0 < cp->num_paths);
728   cp->num_paths--;
729   if ( (NULL == cp->core_mq) &&
730        (NULL != cp->t) &&
731        (NULL == cp->search_h) &&
732        (DESIRED_CONNECTIONS_PER_TUNNEL > cp->num_paths) )
733     cp->search_h
734       = GCD_search (&cp->pid);
735 }
736
737
738 /**
739  * Try adding a @a path to this @a peer.  If the peer already
740  * has plenty of paths, return NULL.
741  *
742  * @param cp peer to which the @a path leads to
743  * @param path a path looking for an owner; may not be fully initialized yet!
744  * @param off offset of @a cp in @a path
745  * @param force force attaching the path
746  * @return NULL if this peer does not care to become a new owner,
747  *         otherwise the node in the peer's path heap for the @a path.
748  */
749 struct GNUNET_CONTAINER_HeapNode *
750 GCP_attach_path (struct CadetPeer *cp,
751                  struct CadetPeerPath *path,
752                  unsigned int off,
753                  int force)
754 {
755   GNUNET_CONTAINER_HeapCostType desirability;
756   struct CadetPeerPath *root;
757   GNUNET_CONTAINER_HeapCostType root_desirability;
758   struct GNUNET_CONTAINER_HeapNode *hn;
759
760   if (NULL == cp->path_heap)
761   {
762     /* #GCP_drop_owned_paths() was already called, we cannot take new ones! */
763     GNUNET_assert (GNUNET_NO == force);
764     return NULL;
765   }
766   desirability = GCPP_get_desirability (path);
767   if (GNUNET_NO == force)
768   {
769     /* FIXME: desirability is not yet initialized; tricky! */
770     if (GNUNET_NO ==
771         GNUNET_CONTAINER_heap_peek2 (cp->path_heap,
772                                      (void **) &root,
773                                      &root_desirability))
774     {
775       root = NULL;
776       root_desirability = 0;
777     }
778
779     if ( (DESIRED_CONNECTIONS_PER_TUNNEL > cp->num_paths) &&
780          (desirability < root_desirability) )
781     {
782       LOG (GNUNET_ERROR_TYPE_DEBUG,
783            "Decided to not attach path %p to peer %s due to undesirability\n",
784            GCPP_2s (path),
785            GCP_2s (cp));
786       return NULL;
787     }
788   }
789
790   LOG (GNUNET_ERROR_TYPE_DEBUG,
791        "Attaching path %s to peer %s (%s)\n",
792        GCPP_2s (path),
793        GCP_2s (cp),
794        (GNUNET_NO == force) ? "desirable" : "forced");
795
796   /* Yes, we'd like to add this path, add to our heap */
797   hn = GNUNET_CONTAINER_heap_insert (cp->path_heap,
798                                      path,
799                                      desirability);
800
801   /* Consider maybe dropping other paths because of the new one */
802   if (GNUNET_CONTAINER_heap_get_size (cp->path_heap) >=
803       2 * DESIRED_CONNECTIONS_PER_TUNNEL)
804   {
805     /* Now we have way too many, drop least desirable UNLESS it is in use!
806        (Note that this intentionally keeps highly desireable, but currently
807        unused paths around in the hope that we might be able to switch, even
808        if the number of paths exceeds the threshold.) */
809     root = GNUNET_CONTAINER_heap_peek (cp->path_heap);
810     if ( (path != root) &&
811          (NULL ==
812           GCPP_get_connection (root,
813                                cp,
814                                GCPP_get_length (root) - 1)) )
815     {
816       /* Got plenty of paths to this destination, and this is a low-quality
817          one that we don't care, allow it to die. */
818       GNUNET_assert (root ==
819                      GNUNET_CONTAINER_heap_remove_root (cp->path_heap));
820       GCPP_release (root);
821     }
822   }
823   return hn;
824 }
825
826
827 /**
828  * This peer can no longer own @a path as the path
829  * has been extended and a peer further down the line
830  * is now the new owner.
831  *
832  * @param cp old owner of the @a path
833  * @param path path where the ownership is lost
834  * @param hn note in @a cp's path heap that must be deleted
835  */
836 void
837 GCP_detach_path (struct CadetPeer *cp,
838                  struct CadetPeerPath *path,
839                  struct GNUNET_CONTAINER_HeapNode *hn)
840 {
841   LOG (GNUNET_ERROR_TYPE_DEBUG,
842        "Detatching path %s from peer %s\n",
843        GCPP_2s (path),
844        GCP_2s (cp));
845   GNUNET_assert (path ==
846                  GNUNET_CONTAINER_heap_remove_node (hn));
847 }
848
849
850 /**
851  * Add a @a connection to this @a cp.
852  *
853  * @param cp peer via which the @a connection goes
854  * @param cc the connection to add
855  */
856 void
857 GCP_add_connection (struct CadetPeer *cp,
858                     struct CadetConnection *cc)
859 {
860   LOG (GNUNET_ERROR_TYPE_DEBUG,
861        "Adding connection %s to peer %s\n",
862        GCC_2s (cc),
863        GCP_2s (cp));
864   GNUNET_assert (GNUNET_OK ==
865                  GNUNET_CONTAINER_multishortmap_put (cp->connections,
866                                                      &GCC_get_id (cc)->connection_of_tunnel,
867                                                      cc,
868                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
869 }
870
871
872 /**
873  * Remove a @a connection that went via this @a cp.
874  *
875  * @param cp peer via which the @a connection went
876  * @param cc the connection to remove
877  */
878 void
879 GCP_remove_connection (struct CadetPeer *cp,
880                        struct CadetConnection *cc)
881 {
882   LOG (GNUNET_ERROR_TYPE_DEBUG,
883        "Removing connection %s from peer %s\n",
884        GCC_2s (cc),
885        GCP_2s (cp));
886   GNUNET_assert (GNUNET_YES ==
887                  GNUNET_CONTAINER_multishortmap_remove (cp->connections,
888                                                         &GCC_get_id (cc)->connection_of_tunnel,
889                                                         cc));
890 }
891
892
893 /**
894  * Retrieve the CadetPeer stucture associated with the
895  * peer. Optionally create one and insert it in the appropriate
896  * structures if the peer is not known yet.
897  *
898  * @param peer_id Full identity of the peer.
899  * @param create #GNUNET_YES if a new peer should be created if unknown.
900  *               #GNUNET_NO to return NULL if peer is unknown.
901  * @return Existing or newly created peer structure.
902  *         NULL if unknown and not requested @a create
903  */
904 struct CadetPeer *
905 GCP_get (const struct GNUNET_PeerIdentity *peer_id,
906          int create)
907 {
908   struct CadetPeer *cp;
909
910   cp = GNUNET_CONTAINER_multipeermap_get (peers,
911                                           peer_id);
912   if (NULL != cp)
913     return cp;
914   if (GNUNET_NO == create)
915     return NULL;
916   cp = GNUNET_new (struct CadetPeer);
917   cp->pid = *peer_id;
918   cp->connections = GNUNET_CONTAINER_multishortmap_create (32,
919                                                            GNUNET_YES);
920   cp->path_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
921   GNUNET_assert (GNUNET_YES ==
922                  GNUNET_CONTAINER_multipeermap_put (peers,
923                                                     &cp->pid,
924                                                     cp,
925                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
926   LOG (GNUNET_ERROR_TYPE_DEBUG,
927        "Creating peer %s\n",
928        GCP_2s (cp));
929   return cp;
930 }
931
932
933 /**
934  * Obtain the peer identity for a `struct CadetPeer`.
935  *
936  * @param cp our peer handle
937  * @return the peer identity
938  */
939 const struct GNUNET_PeerIdentity *
940 GCP_get_id (struct CadetPeer *cp)
941 {
942   return &cp->pid;
943 }
944
945
946 /**
947  * Iterate over all known peers.
948  *
949  * @param iter Iterator.
950  * @param cls Closure for @c iter.
951  */
952 void
953 GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter,
954                  void *cls)
955 {
956   GNUNET_CONTAINER_multipeermap_iterate (peers,
957                                          iter,
958                                          cls);
959 }
960
961
962 /**
963  * Count the number of known paths toward the peer.
964  *
965  * @param cp Peer to get path info.
966  * @return Number of known paths.
967  */
968 unsigned int
969 GCP_count_paths (const struct CadetPeer *cp)
970 {
971   return cp->num_paths;
972 }
973
974
975 /**
976  * Iterate over the paths to a peer.
977  *
978  * @param cp Peer to get path info.
979  * @param callback Function to call for every path.
980  * @param callback_cls Closure for @a callback.
981  * @return Number of iterated paths.
982  */
983 unsigned int
984 GCP_iterate_paths (struct CadetPeer *cp,
985                    GCP_PathIterator callback,
986                    void *callback_cls)
987 {
988   unsigned int ret = 0;
989
990   LOG (GNUNET_ERROR_TYPE_DEBUG,
991        "Iterating over paths to peer %s%s\n",
992        GCP_2s (cp),
993        (NULL == cp->core_mq) ? "" : " including direct link");
994   if (NULL != cp->core_mq)
995   {
996     struct CadetPeerPath *path;
997
998     path = GCPP_get_path_from_route (1,
999                                      &cp->pid);
1000     ret++;
1001     if (GNUNET_NO ==
1002         callback (callback_cls,
1003                   path,
1004                   1))
1005       return ret;
1006   }
1007   for (unsigned int i=0;i<cp->path_dll_length;i++)
1008   {
1009     for (struct CadetPeerPathEntry *pe = cp->path_heads[i];
1010          NULL != pe;
1011          pe = pe->next)
1012     {
1013       ret++;
1014       if (GNUNET_NO ==
1015           callback (callback_cls,
1016                     pe->path,
1017                     i))
1018         return ret;
1019     }
1020   }
1021   return ret;
1022 }
1023
1024
1025 /**
1026  * Iterate over the paths to @a cp where
1027  * @a cp is at distance @a dist from us.
1028  *
1029  * @param cp Peer to get path info.
1030  * @param dist desired distance of @a cp to us on the path
1031  * @param callback Function to call for every path.
1032  * @param callback_cls Closure for @a callback.
1033  * @return Number of iterated paths.
1034  */
1035 unsigned int
1036 GCP_iterate_paths_at (struct CadetPeer *cp,
1037                       unsigned int dist,
1038                       GCP_PathIterator callback,
1039                       void *callback_cls)
1040 {
1041   unsigned int ret = 0;
1042
1043   if (dist >= cp->path_dll_length)
1044   {
1045     LOG (GNUNET_ERROR_TYPE_DEBUG,
1046          "Asked to look for paths at distance %u, but maximum for me is < %u\n",
1047          dist,
1048          cp->path_dll_length);
1049     return 0;
1050   }
1051   for (struct CadetPeerPathEntry *pe = cp->path_heads[dist];
1052        NULL != pe;
1053        pe = pe->next)
1054   {
1055     if (GNUNET_NO ==
1056         callback (callback_cls,
1057                   pe->path,
1058                   dist))
1059       return ret;
1060     ret++;
1061   }
1062   return ret;
1063 }
1064
1065
1066 /**
1067  * Get the tunnel towards a peer.
1068  *
1069  * @param cp Peer to get from.
1070  * @param create #GNUNET_YES to create a tunnel if we do not have one
1071  * @return Tunnel towards peer.
1072  */
1073 struct CadetTunnel *
1074 GCP_get_tunnel (struct CadetPeer *cp,
1075                 int create)
1076 {
1077   if (NULL == cp)
1078     return NULL;
1079   if ( (NULL != cp->t) ||
1080        (GNUNET_NO == create) )
1081     return cp->t;
1082   cp->t = GCT_create_tunnel (cp);
1083   consider_peer_activate (cp);
1084   return cp->t;
1085 }
1086
1087
1088 /**
1089  * Hello offer was passed to the transport service. Mark it
1090  * as done.
1091  *
1092  * @param cls the `struct CadetPeer` where the offer completed
1093  */
1094 static void
1095 hello_offer_done (void *cls)
1096 {
1097   struct CadetPeer *cp = cls;
1098
1099   cp->hello_offer = NULL;
1100 }
1101
1102
1103 /**
1104  * We got a HELLO for a @a peer, remember it, and possibly
1105  * trigger adequate actions (like trying to connect).
1106  *
1107  * @param cp the peer we got a HELLO for
1108  * @param hello the HELLO to remember
1109  */
1110 void
1111 GCP_set_hello (struct CadetPeer *cp,
1112                const struct GNUNET_HELLO_Message *hello)
1113 {
1114   struct GNUNET_HELLO_Message *mrg;
1115
1116   LOG (GNUNET_ERROR_TYPE_DEBUG,
1117        "Got %u byte HELLO for peer %s\n",
1118        (unsigned int) GNUNET_HELLO_size (hello),
1119        GCP_2s (cp));
1120   if (NULL != cp->hello_offer)
1121   {
1122     GNUNET_TRANSPORT_offer_hello_cancel (cp->hello_offer);
1123     cp->hello_offer = NULL;
1124   }
1125   if (NULL != cp->hello)
1126   {
1127     mrg = GNUNET_HELLO_merge (hello,
1128                               cp->hello);
1129     GNUNET_free (cp->hello);
1130     cp->hello = mrg;
1131   }
1132   else
1133   {
1134     cp->hello = GNUNET_memdup (hello,
1135                                GNUNET_HELLO_size (hello));
1136   }
1137   cp->hello_offer
1138     = GNUNET_TRANSPORT_offer_hello (cfg,
1139                                     GNUNET_HELLO_get_header (cp->hello) ,
1140                                     &hello_offer_done,
1141                                     cp);
1142   /* New HELLO means cp's destruction time may change... */
1143   consider_peer_destroy (cp);
1144 }
1145
1146
1147 /**
1148  * The tunnel to the given peer no longer exists, remove it from our
1149  * data structures, and possibly clean up the peer itself.
1150  *
1151  * @param cp the peer affected
1152  * @param t the dead tunnel
1153  */
1154 void
1155 GCP_drop_tunnel (struct CadetPeer *cp,
1156                  struct CadetTunnel *t)
1157 {
1158   LOG (GNUNET_ERROR_TYPE_DEBUG,
1159        "Dropping tunnel %s to peer %s\n",
1160        GCT_2s (t),
1161        GCP_2s (cp));
1162   GNUNET_assert (cp->t == t);
1163   cp->t = NULL;
1164   consider_peer_destroy (cp);
1165 }
1166
1167
1168 /**
1169  * Test if @a cp has a core-level connection
1170  *
1171  * @param cp peer to test
1172  * @return #GNUNET_YES if @a cp has a core-level connection
1173  */
1174 int
1175 GCP_has_core_connection (struct CadetPeer *cp)
1176 {
1177   return (NULL != cp->core_mq) ? GNUNET_YES : GNUNET_NO;
1178 }
1179
1180
1181 /**
1182  * Start message queue change notifications.
1183  *
1184  * @param cp peer to notify for
1185  * @param cb function to call if mq becomes available or unavailable
1186  * @param cb_cls closure for @a cb
1187  * @return handle to cancel request
1188  */
1189 struct GCP_MessageQueueManager *
1190 GCP_request_mq (struct CadetPeer *cp,
1191                 GCP_MessageQueueNotificationCallback cb,
1192                 void *cb_cls)
1193 {
1194   struct GCP_MessageQueueManager *mqm;
1195
1196   mqm = GNUNET_new (struct GCP_MessageQueueManager);
1197   mqm->cb = cb;
1198   mqm->cb_cls = cb_cls;
1199   mqm->cp = cp;
1200   GNUNET_CONTAINER_DLL_insert (cp->mqm_head,
1201                                cp->mqm_tail,
1202                                mqm);
1203   LOG (GNUNET_ERROR_TYPE_DEBUG,
1204        "Creating MQM %p for peer %s\n",
1205        mqm,
1206        GCP_2s (cp));
1207   if (NULL != cp->core_mq)
1208     cb (cb_cls,
1209         GNUNET_YES);
1210   return mqm;
1211 }
1212
1213
1214 /**
1215  * Stops message queue change notifications.
1216  *
1217  * @param mqm handle matching request to cancel
1218  * @param last_env final message to transmit, or NULL
1219  */
1220 void
1221 GCP_request_mq_cancel (struct GCP_MessageQueueManager *mqm,
1222                        struct GNUNET_MQ_Envelope *last_env)
1223 {
1224   struct CadetPeer *cp = mqm->cp;
1225
1226   LOG (GNUNET_ERROR_TYPE_DEBUG,
1227        "Destroying MQM %p for peer %s%s\n",
1228        mqm,
1229        GCP_2s (cp),
1230        (NULL == last_env) ? "" : " with last ditch transmission");
1231   if (NULL != mqm->env)
1232     GNUNET_MQ_discard (mqm->env);
1233   if (NULL != last_env)
1234   {
1235     if (NULL != cp->core_mq)
1236       GNUNET_MQ_send (cp->core_mq,
1237                       last_env);
1238     else
1239       GNUNET_MQ_discard (last_env);
1240   }
1241   GNUNET_CONTAINER_DLL_remove (cp->mqm_head,
1242                                cp->mqm_tail,
1243                                mqm);
1244   GNUNET_free (mqm);
1245 }
1246
1247
1248 /**
1249  * Send the message in @a env to @a cp, overriding queueing logic.
1250  * This function should only be used to send error messages outside
1251  * of flow and congestion control, similar to ICMP.  Note that
1252  * the envelope may be silently discarded as well.
1253  *
1254  * @param cp peer to send the message to
1255  * @param env envelope with the message to send
1256  */
1257 void
1258 GCP_send_ooo (struct CadetPeer *cp,
1259               struct GNUNET_MQ_Envelope *env)
1260 {
1261   LOG (GNUNET_ERROR_TYPE_DEBUG,
1262        "Sending message to %s out of management\n",
1263        GCP_2s (cp));
1264   if (NULL == cp->core_mq)
1265   {
1266     GNUNET_MQ_discard (env);
1267     return;
1268   }
1269   GNUNET_MQ_send (cp->core_mq,
1270                   env);
1271 }
1272
1273
1274
1275
1276 /* end of gnunet-service-cadet-new_peer.c */