e39558c0b829b8b3fb08c8038650c49a9cad0771
[oweals/gnunet.git] / src / mesh / mesh_tunnel_tree.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001 - 2011 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file mesh/mesh_tunnel_tree.c
23  * @brief Tunnel tree handling functions
24  * @author Bartlomiej Polot
25  */
26
27 #include "mesh.h"
28 #include "mesh_tunnel_tree.h"
29
30 #define MESH_TREE_DEBUG GNUNET_YES
31
32
33 /**
34  * Node of path tree for a tunnel
35  */
36 struct MeshTunnelTreeNode
37 {
38   /**
39    * Peer this node describes
40    */
41   GNUNET_PEER_Id peer;
42
43   /**
44    * Parent node in the tree
45    */
46   struct MeshTunnelTreeNode *parent;
47
48   /**
49    * DLL of siblings
50    */
51   struct MeshTunnelTreeNode *next;
52
53   /**
54    * DLL of siblings
55    */
56   struct MeshTunnelTreeNode *prev;
57
58   /**
59    * DLL of children
60    */
61   struct MeshTunnelTreeNode *children_head;
62
63   /**
64    * DLL of children
65    */
66   struct MeshTunnelTreeNode *children_tail;
67
68     /**
69      * Status of the peer in the tunnel
70      */
71   enum MeshPeerState status;
72 };
73
74
75 /**
76  * Tree to reach all peers in the tunnel
77  */
78 struct MeshTunnelTree
79 {
80   /**
81    * Root node of peer tree
82    */
83   struct MeshTunnelTreeNode *root;
84
85   /**
86    * Node that represents our position in the tree (for non local tunnels)
87    */
88   struct MeshTunnelTreeNode *me;
89
90   /**
91    * DLL of disconneted nodes
92    */
93   struct MeshTunnelTreeNode *disconnected_head;
94
95   /**
96    * DLL of disconneted nodes
97    */
98   struct MeshTunnelTreeNode *disconnected_tail;
99
100   /**
101    * Cache of all peers and the first hop to them.
102    * Indexed by PeerIdentity, contains a pointer to the PeerIdentity
103    * of 1st hop.
104    */
105   struct GNUNET_CONTAINER_MultiHashMap *first_hops;
106
107 };
108
109
110 /**
111  * Create a new path
112  *
113  * @param lenght How many hops will the path have.
114  *
115  * @return A newly allocated path with a peer array of the specified length.
116  */
117 struct MeshPeerPath *
118 path_new (unsigned int length)
119 {
120   struct MeshPeerPath *p;
121
122   p = GNUNET_malloc (sizeof (struct MeshPeerPath));
123   if (length > 0)
124   {
125     p->length = length;
126     p->peers = GNUNET_malloc (length * sizeof (GNUNET_PEER_Id));
127   }
128   return p;
129 }
130
131
132 /**
133  * Invert the path
134  *
135  * @param p the path to invert
136  */
137 void
138 path_invert (struct MeshPeerPath *path)
139 {
140   GNUNET_PEER_Id aux;
141   unsigned int i;
142
143   for (i = 0; i < path->length / 2; i++)
144   {
145     aux = path->peers[i];
146     path->peers[i] = path->peers[path->length - i - 1];
147     path->peers[path->length - i - 1] = aux;
148   }
149 }
150
151
152 /**
153  * Duplicate a path, incrementing short peer's rc.
154  *
155  * @param p The path to duplicate.
156  */
157 struct MeshPeerPath *
158 path_duplicate (struct MeshPeerPath *path)
159 {
160   struct MeshPeerPath *aux;
161   unsigned int i;
162
163   aux = path_new (path->length);
164   memcpy (aux->peers, path->peers, path->length * sizeof (GNUNET_PEER_Id));
165   for (i = 0; i < path->length; i++)
166     GNUNET_PEER_change_rc (path->peers[i], 1);
167   return aux;
168 }
169
170
171 /**
172  * Recusively update the info about what is the first hop to reach the node
173  *
174  * @param tree Tree this nodes belongs to.
175  * @param parent_id Short ID from node form which to start updating.
176  * @param hop If known, ID of the first hop.
177  *            If not known, NULL to find out and pass on children.
178  */
179 static void
180 tree_node_update_first_hops (struct MeshTunnelTree *tree,
181                              struct MeshTunnelTreeNode *parent,
182                              struct GNUNET_PeerIdentity *hop);
183
184
185 /**
186  * Get the length of a path
187  *
188  * @param path The path to measure, with the local peer at any point of it
189  *
190  * @return Number of hops to reach destination
191  *         UINT_MAX in case the peer is not in the path
192  */
193 unsigned int
194 path_get_length (struct MeshPeerPath *path)
195 {
196   if (NULL == path)
197     return UINT_MAX;
198   return path->length;
199 }
200
201
202 /**
203  * Get the cost of the path relative to the already built tunnel tree
204  *
205  * @param t The tunnel tree to which compare
206  * @param path The individual path to reach a peer
207  *
208  * @return Number of hops to reach destination, UINT_MAX in case the peer is not
209  * in the path
210  *
211  * TODO: remove dummy implementation, look into the tunnel tree
212  */
213 unsigned int
214 path_get_cost (struct MeshTunnelTree *t, struct MeshPeerPath *path)
215 {
216   return path_get_length (path);
217 }
218
219
220 /**
221  * Destroy the path and free any allocated resources linked to it
222  *
223  * @param p the path to destroy
224  *
225  * @return GNUNET_OK on success
226  */
227 int
228 path_destroy (struct MeshPeerPath *p)
229 {
230   if (NULL == p)
231     return GNUNET_OK;
232   GNUNET_PEER_decrement_rcs (p->peers, p->length);
233   GNUNET_free_non_null (p->peers);
234   GNUNET_free (p);
235   return GNUNET_OK;
236 }
237
238
239
240 /**
241  * Allocates and initializes a new node.
242  * Sets ID and parent of the new node and inserts it in the DLL of the parent
243  *
244  * @param parent Node that will be the parent from the new node, NULL for root
245  * @param peer Short Id of the new node
246  *
247  * @return Newly allocated node
248  */
249 static struct MeshTunnelTreeNode *
250 tree_node_new (struct MeshTunnelTreeNode *parent, GNUNET_PEER_Id peer)
251 {
252   struct MeshTunnelTreeNode *node;
253
254   node = GNUNET_malloc (sizeof (struct MeshTunnelTreeNode));
255   node->peer = peer;
256   GNUNET_PEER_change_rc (peer, 1);
257   node->parent = parent;
258   if (NULL != parent)
259     GNUNET_CONTAINER_DLL_insert (parent->children_head, parent->children_tail,
260                                  node);
261
262   return node;
263 }
264
265
266 /**
267  * Recursively find the given peer.
268  *
269  * @param parent Node where to start looking.
270  * @param peer Peer to find.
271  *
272  * @return Pointer to the node of the peer. NULL if not found.
273  */
274 static struct MeshTunnelTreeNode *
275 tree_node_find_peer (struct MeshTunnelTreeNode *parent, GNUNET_PEER_Id peer_id)
276 {
277   struct MeshTunnelTreeNode *n;
278   struct MeshTunnelTreeNode *r;
279
280   if (parent->peer == peer_id)
281     return parent;
282   for (n = parent->children_head; NULL != n; n = n->next)
283   {
284     r = tree_node_find_peer (n, peer_id);
285     if (NULL != r)
286       return r;
287   }
288   return NULL;
289 }
290
291
292 /**
293  * Recusively update the info about what is the first hop to reach the node
294  *
295  * @param tree Tree this nodes belongs to.
296  * @param parent_id Short ID from node form which to start updating.
297  * @param hop If known, ID of the first hop.
298  *            If not known, NULL to find out and pass on children.
299  */
300 static void
301 tree_node_update_first_hops (struct MeshTunnelTree *tree,
302                              struct MeshTunnelTreeNode *parent,
303                              struct GNUNET_PeerIdentity *hop)
304 {
305   struct GNUNET_PeerIdentity pi;
306   struct GNUNET_PeerIdentity *copy;
307   struct GNUNET_PeerIdentity id;
308   struct MeshTunnelTreeNode *n;
309
310 #if MESH_TREE_DEBUG
311   GNUNET_PEER_resolve (parent->peer, &id);
312   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   Finding first hop for %s.\n",
313               GNUNET_i2s (&id));
314 #endif
315   if (NULL == hop)
316   {
317     struct MeshTunnelTreeNode *aux;
318     struct MeshTunnelTreeNode *old;
319
320     aux = old = parent;
321     while (aux != tree->me)
322     {
323 #if MESH_TREE_DEBUG
324       GNUNET_PEER_resolve (aux->peer, &id);
325       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   ... checking %s.\n",
326                   GNUNET_i2s (&id));
327 #endif
328       old = aux;
329       aux = aux->parent;
330       GNUNET_assert (NULL != aux);
331     }
332 #if MESH_TREE_DEBUG
333     GNUNET_PEER_resolve (old->peer, &id);
334     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   It's %s!\n",
335                 GNUNET_i2s (&id));
336 #endif
337     hop = &pi;
338     GNUNET_PEER_resolve (old->peer, hop);
339   }
340   GNUNET_PEER_resolve (parent->peer, &id);
341   copy = GNUNET_CONTAINER_multihashmap_get (tree->first_hops, &id.hashPubKey);
342   if (NULL == copy)
343     copy = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
344   *copy = *hop;
345
346   (void) GNUNET_CONTAINER_multihashmap_put (tree->first_hops, &id.hashPubKey,
347                                             copy,
348                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
349
350   for (n = parent->children_head; NULL != n; n = n->next)
351   {
352     tree_node_update_first_hops (tree, n, hop);
353   }
354 }
355
356
357 static void
358 tree_node_debug (struct MeshTunnelTreeNode *n, uint16_t level)
359 {
360   struct MeshTunnelTreeNode *c;
361   struct GNUNET_PeerIdentity id;;
362   uint16_t i;
363
364   for (i = 0; i < level; i++)
365     fprintf (stderr, "  ");
366   if (n->status == MESH_PEER_READY)
367     fprintf (stderr, "#");
368   if (n->status == MESH_PEER_SEARCHING)
369     fprintf (stderr, "+");
370   if (n->status == MESH_PEER_RELAY)
371     fprintf (stderr, "-");
372   if (n->status == MESH_PEER_RECONNECTING)
373     fprintf (stderr, "*");
374
375   GNUNET_PEER_resolve (n->peer, &id);
376   fprintf (stderr, "%s, [%u, %p] ", GNUNET_i2s (&id), n->peer, n);
377   if (NULL != n->parent)
378   {
379     GNUNET_PEER_resolve (n->parent->peer, &id);
380     fprintf (stderr, "(-> %s [%u])\n", GNUNET_i2s (&id), n->parent->peer);
381   }
382   else
383     fprintf (stderr, "(root)\n");
384   for (c = n->children_head; NULL != c; c = c->next)
385     tree_node_debug (c, level + 1);
386 }
387
388
389 /**
390  * Destroys and frees the node and all children
391  *
392  * @param n Parent node to be destroyed
393  */
394 static void
395 tree_node_destroy (struct MeshTunnelTreeNode *parent)
396 {
397   struct MeshTunnelTreeNode *n;
398   struct MeshTunnelTreeNode *next;
399
400 #if MESH_TREE_DEBUG
401   struct GNUNET_PeerIdentity id;
402
403   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree: Destroying node %u\n",
404               parent->peer);
405   GNUNET_PEER_resolve (parent->peer, &id);
406   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   (%s)\n", GNUNET_i2s (&id));
407 #endif
408   n = parent->children_head;
409   while (NULL != n)
410   {
411     next = n->next;
412     tree_node_destroy (n);
413     n = next;
414   }
415   GNUNET_PEER_change_rc (parent->peer, -1);
416   if (NULL != parent->parent)
417     GNUNET_CONTAINER_DLL_remove (parent->parent->children_head,
418                                  parent->parent->children_tail, parent);
419   GNUNET_free (parent);
420 }
421
422
423
424 /**
425  * Create a new tunnel tree associated to a tunnel
426  *
427  * @param t Tunnel this tree will represent
428  * @param peer A short peer id of the root of the tree
429  *
430  * @return A newly allocated and initialized tunnel tree
431  */
432 struct MeshTunnelTree *
433 tree_new (GNUNET_PEER_Id peer)
434 {
435   struct MeshTunnelTree *tree;
436
437   tree = GNUNET_malloc (sizeof (struct MeshTunnelTree));
438   tree->first_hops = GNUNET_CONTAINER_multihashmap_create (32);
439   tree->root = tree_node_new (NULL, peer);
440   tree->root->status = MESH_PEER_ROOT;
441
442   return tree;
443 }
444
445
446 /**
447  * Set the status of a node.
448  *
449  * @param tree Tree.
450  * @param peer A short peer id of local peer.
451  */
452 void
453 tree_set_status (struct MeshTunnelTree *tree, GNUNET_PEER_Id peer,
454                  enum MeshPeerState status)
455 {
456   struct MeshTunnelTreeNode *n;
457
458   n = tree_find_peer (tree, peer);
459   if (NULL == n)
460     return;
461   n->status = status;
462 }
463
464
465 /**
466  * Get the status of a node.
467  *
468  * @param tree Tree whose local id we want to now.
469  *
470  * @return Short peer id of local peer.
471  */
472 enum MeshPeerState
473 tree_get_status (struct MeshTunnelTree *tree, GNUNET_PEER_Id peer)
474 {
475   struct MeshTunnelTreeNode *n;
476
477   n = tree_find_peer (tree, peer);
478   if (NULL == n)
479     return MESH_PEER_INVALID;
480   return n->status;
481 }
482
483
484 /**
485  * Get the id of the predecessor of the local node.
486  *
487  * @param tree Tree whose local id we want to now.
488  *
489  * @return Short peer id of local peer.
490  */
491 GNUNET_PEER_Id
492 tree_get_predecessor (struct MeshTunnelTree *tree)
493 {
494   if (NULL != tree->me && NULL != tree->me->parent)
495     return tree->me->parent->peer;
496   else
497     return (GNUNET_PEER_Id) 0;
498 }
499
500
501 /**
502  * Find the first peer whom to send a packet to go down this path
503  *
504  * @param t The tunnel tree to use
505  * @param peer The peerinfo of the peer we are trying to reach
506  *
507  * @return peerinfo of the peer who is the first hop in the tunnel
508  *         NULL on error
509  */
510 struct GNUNET_PeerIdentity *
511 tree_get_first_hop (struct MeshTunnelTree *t, GNUNET_PEER_Id peer)
512 {
513   struct GNUNET_PeerIdentity id;
514   struct GNUNET_PeerIdentity *r;
515
516   GNUNET_PEER_resolve (peer, &id);
517   r = GNUNET_CONTAINER_multihashmap_get (t->first_hops, &id.hashPubKey);
518   if (NULL == r)
519   {
520     struct MeshTunnelTreeNode *n;
521
522     n = tree_find_peer (t, peer);
523     if (NULL != t->me && NULL != n)
524     {
525       tree_node_update_first_hops (t, n, NULL);
526       r = GNUNET_CONTAINER_multihashmap_get (t->first_hops, &id.hashPubKey);
527       GNUNET_assert (NULL != r);
528     }
529     else
530     {
531       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
532                   "Tree structure inconsistent! me: %p, n: %p", t->me, n);
533       GNUNET_break (0);
534     }
535   }
536
537   return r;
538 }
539
540
541 /**
542  * Find the given peer in the tree.
543  *
544  * @param tree Tree where to look for the peer.
545  * @param peer Peer to find.
546  *
547  * @return Pointer to the node of the peer. NULL if not found.
548  */
549 struct MeshTunnelTreeNode *
550 tree_find_peer (struct MeshTunnelTree *tree, GNUNET_PEER_Id peer_id)
551 {
552   return tree_node_find_peer (tree->root, peer_id);
553 }
554
555
556 /**
557  * Recusively mark peer and children as disconnected, notify client
558  *
559  * @param tree Tree this node belongs to
560  * @param parent Node to be clean, potentially with children
561  * @param cb Callback to use to notify about disconnected peers.
562  */
563 static void
564 tree_mark_peers_disconnected (struct MeshTunnelTree *tree,
565                               struct MeshTunnelTreeNode *parent,
566                               MeshTreeCallback cb, void *cbcls)
567 {
568   struct GNUNET_PeerIdentity *pi;
569   struct GNUNET_PeerIdentity id;
570   struct MeshTunnelTreeNode *n;
571
572   for (n = parent->children_head; NULL != n; n = n->next)
573   {
574     tree_mark_peers_disconnected (tree, n, cb, cbcls);
575   }
576   if (MESH_PEER_READY == parent->status)
577   {
578     if (NULL != cb)
579       cb (cbcls, parent->peer);
580     parent->status = MESH_PEER_RECONNECTING;
581   }
582
583   /* Remove and free info about first hop */
584   GNUNET_PEER_resolve (parent->peer, &id);
585   pi = GNUNET_CONTAINER_multihashmap_get (tree->first_hops, &id.hashPubKey);
586   GNUNET_CONTAINER_multihashmap_remove_all (tree->first_hops, &id.hashPubKey);
587   if (NULL != pi)
588     GNUNET_free (pi);
589 }
590
591
592 /**
593  * Iterate over all children of the local node.
594  *
595  * @param tree Tree to use. Must have "me" set.
596  * @param cb Callback to call over each child.
597  * @param cls Closure.
598  */
599 void
600 tree_iterate_children (struct MeshTunnelTree *tree, MeshTreeCallback cb,
601                        void *cls)
602 {
603   struct MeshTunnelTreeNode *n;
604
605   if (NULL == tree->me)
606   {
607     GNUNET_break (0);
608     return;
609   }
610   for (n = tree->me->children_head; NULL != n; n = n->next)
611   {
612     cb (cls, n->peer);
613   }
614 }
615
616
617 /**
618  * Recusively update the info about what is the first hop to reach the node
619  *
620  * @param tree Tree this nodes belongs to.
621  * @param parent_id Short ID from node form which to start updating.
622  * @param hop If known, ID of the first hop.
623  *            If not known, NULL to find out and pass on children.
624  */
625 void
626 tree_update_first_hops (struct MeshTunnelTree *tree, GNUNET_PEER_Id parent_id,
627                         struct GNUNET_PeerIdentity *hop)
628 {
629   tree_node_update_first_hops (tree, tree_find_peer (tree, parent_id), hop);
630 }
631
632
633 /**
634  * Delete the current path to the peer, including all now unused relays.
635  * The destination peer is NOT destroyed, it is returned in order to either set
636  * a new path to it or destroy it explicitly, taking care of it's child nodes.
637  *
638  * @param t Tunnel tree where to delete the path from.
639  * @param peer Destination peer whose path we want to remove.
640  * @param cb Callback to use to notify about disconnected peers.
641  * @param cbcls Closure for cb.
642  *
643  * @return pointer to the pathless node.
644  *         NULL when not found
645  */
646 struct MeshTunnelTreeNode *
647 tree_del_path (struct MeshTunnelTree *t, GNUNET_PEER_Id peer_id,
648                MeshTreeCallback cb, void *cbcls)
649 {
650   struct MeshTunnelTreeNode *parent;
651   struct MeshTunnelTreeNode *node;
652   struct MeshTunnelTreeNode *n;
653
654 #if MESH_TREE_DEBUG
655   struct GNUNET_PeerIdentity id;
656
657   GNUNET_PEER_resolve (peer_id, &id);
658   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   Deleting path to %s.\n",
659               GNUNET_i2s (&id));
660 #endif
661   if (peer_id == t->root->peer)
662     return NULL;
663
664   for (n = t->disconnected_head; NULL != n; n = n->next)
665   {
666     if (n->peer == peer_id)
667     {
668       /* Was already pathless, waiting for reconnection */
669       GNUNET_CONTAINER_DLL_remove (t->disconnected_head, t->disconnected_tail,
670                                    n);
671       return n;
672     }
673   }
674   n = tree_find_peer (t, peer_id);
675   if (NULL == n)
676     return NULL;
677   node = n;
678
679   parent = n->parent;
680   GNUNET_CONTAINER_DLL_remove (parent->children_head, parent->children_tail, n);
681   n->parent = NULL;
682
683   while (MESH_PEER_RELAY == parent->status && NULL == parent->children_head)
684   {
685 #if MESH_TREE_DEBUG
686     GNUNET_PEER_resolve (parent->peer, &id);
687     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   Deleting node %s.\n",
688                 GNUNET_i2s (&id));
689 #endif
690     n = parent->parent;
691     tree_node_destroy (parent);
692     parent = n;
693   }
694 #if MESH_TREE_DEBUG
695   GNUNET_PEER_resolve (parent->peer, &id);
696   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   Not deleted peer %s.\n",
697               GNUNET_i2s (&id));
698 #endif
699
700   tree_mark_peers_disconnected (t, node, cb, cbcls);
701
702   return node;
703 }
704
705
706 /**
707  * Return a newly allocated individual path to reach a peer from the local peer,
708  * according to the path tree of some tunnel.
709  *
710  * @param t Tunnel from which to read the path tree
711  * @param peer_info Destination peer to whom we want a path
712  *
713  * @return A newly allocated individual path to reach the destination peer.
714  *         Path must be destroyed afterwards.
715  */
716 struct MeshPeerPath *
717 tree_get_path_to_peer (struct MeshTunnelTree *t, GNUNET_PEER_Id peer)
718 {
719   struct MeshTunnelTreeNode *n;
720   struct MeshPeerPath *p;
721
722   n = tree_find_peer (t, peer);
723   if (NULL == n)
724     return NULL;
725   p = path_new (0);
726
727   /* Building the path (inverted!) */
728   while (n->peer != 1)
729   {
730     GNUNET_array_append (p->peers, p->length, n->peer);
731     GNUNET_PEER_change_rc (n->peer, 1);
732     n = n->parent;
733     if (NULL == n)
734     {
735       path_destroy (p);
736       return NULL;
737     }
738   }
739   GNUNET_array_append (p->peers, p->length, 1);
740   GNUNET_PEER_change_rc (1, 1);
741
742   path_invert (p);
743
744   return p;
745 }
746
747
748
749 /**
750  * Integrate a stand alone path into the tunnel tree.
751  * If the peer toward which the new path is already in the tree, the peer
752  * and its children will be maked as disconnected and the callback
753  * will be called on each one of them. They will be maked as online only after
754  * receiving a PATH ACK for the new path for each one of them, so the caller
755  * should take care of sending a new CREATE PATH message for each disconnected
756  * peer.
757  *
758  * @param t Tunnel where to add the new path.
759  * @param p Path to be integrated.
760  * @param cb Callback to use to notify about peers temporarily disconnecting.
761  * @param cbcls Closure for cb.
762  *
763  * @return GNUNET_OK in case of success.
764  *         GNUNET_SYSERR in case of error.
765  *
766  * TODO: optimize
767  * - go backwards on path looking for each peer in the present tree
768  * - do not disconnect peers until new path is created & connected
769  */
770 int
771 tree_add_path (struct MeshTunnelTree *t, const struct MeshPeerPath *p,
772                MeshTreeCallback cb, void *cbcls)
773 {
774   struct MeshTunnelTreeNode *parent;
775   struct MeshTunnelTreeNode *oldnode;
776   struct MeshTunnelTreeNode *n;
777   struct MeshTunnelTreeNode *c;
778   struct GNUNET_PeerIdentity id;
779   int me;
780   unsigned int i;
781
782 #if MESH_TREE_DEBUG
783   GNUNET_PEER_resolve (p->peers[p->length - 1], &id);
784   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
785               "tree:   Adding path [%u] towards peer %s.\n", p->length,
786               GNUNET_i2s (&id));
787 #endif
788
789   GNUNET_assert (0 != p->length);
790   parent = n = t->root;
791   if (n->peer != p->peers[0])
792   {
793     GNUNET_break (0);
794     return GNUNET_SYSERR;
795   }
796   if (1 == p->length)
797     return GNUNET_OK;
798   oldnode = tree_del_path (t, p->peers[p->length - 1], cb, cbcls);
799   /* Look for the first node that is not already present in the tree
800    *
801    * Assuming that the tree is somewhat balanced, O(log n * log N).
802    * - Length of the path is expected to be log N (size of whole network).
803    * - Each level of the tree is expected to have log n children (size of tree).
804    */
805   me = t->root->peer == 1 ? 0 : -1;
806   for (i = 1; i < p->length; i++)
807   {
808 #if MESH_TREE_DEBUG
809     GNUNET_PEER_resolve (p->peers[i], &id);
810     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   Looking for peer %s.\n",
811                 GNUNET_i2s (&id));
812 #endif
813     parent = n;
814     if (p->peers[i] == 1)
815       me = i;
816     for (c = n->children_head; NULL != c; c = c->next)
817     {
818       if (c->peer == p->peers[i])
819       {
820 #if MESH_TREE_DEBUG
821         GNUNET_PEER_resolve (parent->peer, &id);
822         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
823                     "tree:   Found in children of %s.\n", GNUNET_i2s (&id));
824 #endif
825         n = c;
826         break;
827       }
828     }
829     /*  If we couldn't find a child equal to path[i], we have reached the end
830      * of the common path. */
831     if (parent == n)
832       break;
833   }
834 #if MESH_TREE_DEBUG
835   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   All childen visited.\n");
836 #endif
837   /* Add the rest of the path as a branch from parent. */
838   while (i < p->length)
839   {
840 #if MESH_TREE_DEBUG
841     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   Adding peer %u to %u.\n",
842                 p->peers[i], parent->peer);
843     GNUNET_PEER_resolve (p->peers[i], &id);
844     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   Adding peer %s.\n",
845                 GNUNET_i2s (&id));
846     GNUNET_PEER_resolve (parent->peer, &id);
847     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:     to %s.\n",
848                 GNUNET_i2s (&id));
849 #endif
850
851     if (i == p->length - 1 && NULL != oldnode)
852     {
853 #if MESH_TREE_DEBUG
854       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
855                   "tree:   Putting old node into place.\n");
856 #endif
857       oldnode->parent = parent;
858       GNUNET_CONTAINER_DLL_insert (parent->children_head, parent->children_tail,
859                                    oldnode);
860       tree_node_update_first_hops (t, oldnode, NULL);
861       n = oldnode;
862     }
863     else
864     {
865 #if MESH_TREE_DEBUG
866       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   Creating new node.\n");
867 #endif
868       n = tree_node_new (parent, p->peers[i]);
869       n->status = MESH_PEER_RELAY;
870       if (n->peer == 1)
871       {
872         t->me = n;
873         me = i;
874       }
875     }
876     i++;
877     parent = n;
878   }
879   n->status = MESH_PEER_SEARCHING;
880
881   GNUNET_break (-1 != me);
882
883   /* Add info about first hop into hashmap. */
884   if (-1 != me && me < p->length - 1)
885   {
886 #if MESH_TREE_DEBUG
887     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
888                 "MESH:   finding first hop (own pos %d/%u)\n", me,
889                 p->length - 1);
890 #endif
891     GNUNET_PEER_resolve (p->peers[me + 1], &id);
892     tree_update_first_hops (t, p->peers[me + 1], &id);
893   }
894 #if MESH_TREE_DEBUG
895   else
896   {
897     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
898                 "MESH:   was last in path, not updating first hops (%d/%u)\n",
899                 me, p->length - 1);
900   }
901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree:   New node added.\n");
902 #endif
903   return GNUNET_OK;
904 }
905
906
907 /**
908  * Notifies a tree that a connection it might be using is broken.
909  * Marks all peers down the paths as disconnected and notifies the client.
910  *
911  * @param t Tree to use.
912  * @param p1 Short id of one of the peers (order unimportant)
913  * @param p2 Short id of one of the peers (order unimportant)
914  * @param cb Function to call for every peer that is marked as disconnected.
915  * @param cbcls Closure for cb.
916  *
917  * @return Short ID of the first disconnected peer in the tree.
918  */
919 GNUNET_PEER_Id
920 tree_notify_connection_broken (struct MeshTunnelTree *t, GNUNET_PEER_Id p1,
921                                GNUNET_PEER_Id p2, MeshTreeCallback cb,
922                                void *cbcls)
923 {
924   struct MeshTunnelTreeNode *n;
925   struct MeshTunnelTreeNode *c;
926
927   n = tree_find_peer (t, p1);
928   if (NULL == n)
929     return 0;
930   if (NULL != n->parent && n->parent->peer == p2)
931   {
932     tree_mark_peers_disconnected (t, n, cb, cbcls);
933     GNUNET_CONTAINER_DLL_remove (n->parent->children_head,
934                                  n->parent->children_tail, n);
935     GNUNET_CONTAINER_DLL_insert (t->disconnected_head, t->disconnected_tail, n);
936     return p1;
937   }
938   for (c = n->children_head; NULL != c; c = c->next)
939   {
940     if (c->peer == p2)
941     {
942       tree_mark_peers_disconnected (t, c, cb, cbcls);
943       GNUNET_CONTAINER_DLL_remove (n->children_head, n->children_tail, c);
944       GNUNET_CONTAINER_DLL_insert (t->disconnected_head, t->disconnected_tail,
945                                    c);
946       return p2;
947     }
948   }
949   return 0;
950 }
951
952
953 /**
954  * Deletes a peer from a tunnel, liberating all unused resources on the path to
955  * it. It shouldn't have children, if it has they will be destroyed as well.
956  * If the tree is not local and no longer has any paths, the root node will be
957  * destroyed and marked as NULL.
958  *
959  * @param t Tunnel tree to use.
960  * @param peer Short ID of the peer to remove from the tunnel tree.
961  * @param cb Callback to notify client of disconnected peers.
962  * @param cbcls Closure for cb.
963  *
964  * @return GNUNET_OK or GNUNET_SYSERR
965  */
966 int
967 tree_del_peer (struct MeshTunnelTree *t, GNUNET_PEER_Id peer,
968                MeshTreeCallback cb, void *cbcls)
969 {
970   struct MeshTunnelTreeNode *n;
971
972   n = tree_del_path (t, peer, cb, cbcls);
973   if (NULL == n)
974   {
975     GNUNET_break (0);
976     return GNUNET_YES;
977   }
978   GNUNET_break_op (NULL == n->children_head);
979   tree_node_destroy (n);
980   if (NULL == t->root->children_head && t->me != t->root)
981   {
982     tree_node_destroy (t->root);
983     t->root = NULL;
984     return GNUNET_NO;
985   }
986   return GNUNET_YES;
987 }
988
989
990 /**
991  * Print the tree on stderr
992  *
993  * @param t The tree
994  */
995 void
996 tree_debug (struct MeshTunnelTree *t)
997 {
998   tree_node_debug (t->root, 0);
999 }
1000
1001
1002 /**
1003  * Iterator over hash map peer entries and frees all data in it.
1004  * Used prior to destroying a hashmap. Makes you miss anonymous functions in C.
1005  *
1006  * @param cls closure
1007  * @param key current key code (will no longer contain valid data!!)
1008  * @param value value in the hash map (treated as void *)
1009  * @return GNUNET_YES if we should continue to iterate, GNUNET_NO if not.
1010  */
1011 static int
1012 iterate_free (void *cls, const GNUNET_HashCode * key, void *value)
1013 {
1014   GNUNET_free (value);
1015   return GNUNET_YES;
1016 }
1017
1018
1019 /**
1020  * Destroy the whole tree and free all used memory and Peer_Ids
1021  *
1022  * @param t Tree to be destroyed
1023  */
1024 void
1025 tree_destroy (struct MeshTunnelTree *t)
1026 {
1027 #if MESH_TREE_DEBUG
1028   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tree: Destroying tree\n");
1029 #endif
1030   tree_node_destroy (t->root);
1031   GNUNET_CONTAINER_multihashmap_iterate (t->first_hops, &iterate_free, NULL);
1032   GNUNET_CONTAINER_multihashmap_destroy (t->first_hops);
1033   GNUNET_free (t);
1034 }