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