Fix bug in shortest path implementation
[tinc] / src / graph.c
index da64909..5bec2c1 100644 (file)
@@ -55,6 +55,7 @@
 #include "script.h"
 #include "subnet.h"
 #include "xalloc.h"
+#include "address_cache.h"
 
 /* Implementation of Kruskal's algorithm.
    Running time: O(EN)
@@ -115,11 +116,13 @@ static void mst_kruskal(void) {
        }
 }
 
+// Not putting it into header, the outside world doesn't need to know about it.
+extern void sssp_bfs(void);
+
 /* Implementation of a simple breadth-first search algorithm.
    Running time: O(E)
 */
-
-static void sssp_bfs(void) {
+void sssp_bfs(void) {
        list_t *todo_list = list_alloc(NULL);
 
        /* Clear visited status on nodes */
@@ -138,6 +141,7 @@ static void sssp_bfs(void) {
        myself->prevedge = NULL;
        myself->via = myself;
        myself->distance = 0;
+       myself->weighted_distance = 0;
        list_insert_head(todo_list, myself);
 
        /* Loop while todo_list is filled */
@@ -175,14 +179,15 @@ static void sssp_bfs(void) {
 
                        if(e->to->status.visited
                                        && (!e->to->status.indirect || indirect)
-                                       && (e->to->distance != n->distance + 1 || e->weight >= e->to->prevedge->weight)) {
+                                       && (e->to->distance != n->distance + 1 || e->to->weighted_distance <= n->weighted_distance + e->weight)) {
                                continue;
                        }
 
                        // Only update nexthop if it doesn't increase the path length
 
-                       if(!e->to->status.visited || (e->to->distance == n->distance + 1 && e->weight >= e->to->prevedge->weight)) {
+                       if(!e->to->status.visited || (e->to->distance == n->distance + 1 && e->to->weighted_distance > n->weighted_distance + e->weight)) {
                                e->to->nexthop = (n->nexthop == myself) ? e->to : n->nexthop;
+                               e->to->weighted_distance = n->weighted_distance + e->weight;
                        }
 
                        e->to->status.visited = true;
@@ -224,6 +229,14 @@ static void check_reachability(void) {
 
                                if(n != myself) {
                                        became_reachable_count++;
+
+                                       if(n->connection && n->connection->outgoing) {
+                                               if(!n->address_cache) {
+                                                       n->address_cache = open_address_cache(n);
+                                               }
+
+                                               add_recent_address(n->address_cache, &n->connection->address);
+                                       }
                                }
                        } else {
                                logger(DEBUG_TRAFFIC, LOG_DEBUG, "Node %s (%s) became unreachable",