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