]> git.meshlink.io Git - meshlink/blob - src/graph.c
Prefer routes with lower weight as long as they do not increase the number of hops.
[meshlink] / src / graph.c
1 /*
2     graph.c -- graph algorithms
3     Copyright (C) 2001-2012 Guus Sliepen <guus@tinc-vpn.org>,
4                   2001-2005 Ivo Timmermans
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 /* We need to generate two trees from the graph:
22
23    1. A minimum spanning tree for broadcasts,
24    2. A single-source shortest path tree for unicasts.
25
26    Actually, the first one alone would suffice but would make unicast packets
27    take longer routes than necessary.
28
29    For the MST algorithm we can choose from Prim's or Kruskal's. I personally
30    favour Kruskal's, because we make an extra AVL tree of edges sorted on
31    weights (metric). That tree only has to be updated when an edge is added or
32    removed, and during the MST algorithm we just have go linearly through that
33    tree, adding safe edges until #edges = #nodes - 1. The implementation here
34    however is not so fast, because I tried to avoid having to make a forest and
35    merge trees.
36
37    For the SSSP algorithm Dijkstra's seems to be a nice choice. Currently a
38    simple breadth-first search is presented here.
39
40    The SSSP algorithm will also be used to determine whether nodes are directly,
41    indirectly or not reachable from the source. It will also set the correct
42    destination address and port of a node if possible.
43 */
44
45 #include "system.h"
46
47 #include "splay_tree.h"
48 #include "config.h"
49 #include "connection.h"
50 #include "device.h"
51 #include "edge.h"
52 #include "graph.h"
53 #include "logger.h"
54 #include "netutl.h"
55 #include "node.h"
56 #include "process.h"
57 #include "protocol.h"
58 #include "subnet.h"
59 #include "utils.h"
60 #include "xalloc.h"
61 #include "graph.h"
62
63 /* Implementation of Kruskal's algorithm.
64    Running time: O(E)
65    Please note that sorting on weight is already done by add_edge().
66 */
67
68 static void mst_kruskal(void) {
69         splay_node_t *node, *next;
70         edge_t *e;
71         node_t *n;
72         connection_t *c;
73
74         /* Clear MST status on connections */
75
76         for(node = connection_tree->head; node; node = node->next) {
77                 c = node->data;
78                 c->status.mst = false;
79         }
80
81         logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Running Kruskal's algorithm:");
82
83         /* Clear visited status on nodes */
84
85         for(node = node_tree->head; node; node = node->next) {
86                 n = node->data;
87                 n->status.visited = false;
88         }
89
90         /* Add safe edges */
91
92         for(node = edge_weight_tree->head; node; node = next) {
93                 next = node->next;
94                 e = node->data;
95
96                 if(!e->reverse || (e->from->status.visited && e->to->status.visited))
97                         continue;
98
99                 e->from->status.visited = true;
100                 e->to->status.visited = true;
101
102                 if(e->connection)
103                         e->connection->status.mst = true;
104
105                 if(e->reverse->connection)
106                         e->reverse->connection->status.mst = true;
107
108                 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, " Adding edge %s - %s weight %d", e->from->name,
109                                    e->to->name, e->weight);
110         }
111 }
112
113 /* Implementation of Dijkstra's algorithm.
114    Running time: O(N^2)
115 */
116
117 static void sssp_dijkstra(void) {
118         splay_node_t *node, *to;
119         edge_t *e;
120         node_t *n, *m;
121         list_t *todo_list;
122         list_node_t *lnode, *nnode;
123         bool indirect;
124
125         todo_list = list_alloc(NULL);
126
127         logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Running Dijkstra's algorithm:");
128
129         /* Clear visited status on nodes */
130
131         for(node = node_tree->head; node; node = node->next) {
132                 n = node->data;
133                 n->status.visited = false;
134                 n->status.indirect = true;
135                 n->distance = -1;
136         }
137
138         /* Begin with myself */
139
140         myself->status.indirect = false;
141         myself->nexthop = myself;
142         myself->via = myself;
143         myself->distance = 0;
144         list_insert_head(todo_list, myself);
145
146         /* Loop while todo_list is filled */
147
148         while(todo_list->head) {
149                 n = NULL;
150                 nnode = NULL;
151
152                 /* Select node from todo_list with smallest distance */
153
154                 for(lnode = todo_list->head; lnode; lnode = lnode->next) {
155                         m = lnode->data;
156                         if(!n || m->status.indirect < n->status.indirect || m->distance < n->distance) {
157                                 n = m;
158                                 nnode = lnode;
159                         }
160                 }
161
162                 /* Mark this node as visited and remove it from the todo_list */
163
164                 n->status.visited = true;
165                 list_unlink_node(todo_list, nnode);
166
167                 /* Update distance of neighbours and add them to the todo_list */
168
169                 for(to = n->edge_tree->head; to; to = to->next) {       /* "to" is the edge connected to "from" */
170                         e = to->data;
171
172                         if(e->to->status.visited || !e->reverse)
173                                 continue;
174
175                         /* Situation:
176
177                                    /
178                                   /
179                            ----->(n)---e-->(e->to)
180                                   \
181                                    \
182
183                            Where e is an edge, (n) and (e->to) are nodes.
184                            n->address is set to the e->address of the edge left of n to n.
185                            We are currently examining the edge e right of n from n:
186
187                            - If edge e provides for better reachability of e->to, update e->to.
188                          */
189
190                         if(e->to->distance < 0)
191                                 list_insert_tail(todo_list, e->to);
192
193                         indirect = n->status.indirect || e->options & OPTION_INDIRECT || ((n != myself) && sockaddrcmp(&n->address, &e->reverse->address));
194
195                         if(e->to->distance >= 0 && (!e->to->status.indirect || indirect) && e->to->distance <= n->distance + e->weight)
196                                 continue;
197
198                         e->to->distance = n->distance + e->weight;
199                         e->to->status.indirect = indirect;
200                         e->to->nexthop = (n->nexthop == myself) ? e->to : n->nexthop;
201                         e->to->via = indirect ? n->via : e->to;
202                         e->to->options = e->options;
203
204                         if(e->to->address.sa.sa_family == AF_UNSPEC && e->address.sa.sa_family != AF_UNKNOWN)
205                                 update_node_udp(e->to, &e->address);
206
207                         logger(DEBUG_SCARY_THINGS, LOG_DEBUG, " Updating edge %s - %s weight %d distance %d", e->from->name,
208                                            e->to->name, e->weight, e->to->distance);
209                 }
210         }
211
212         list_free(todo_list);
213 }
214
215 /* Implementation of a simple breadth-first search algorithm.
216    Running time: O(E)
217 */
218
219 static void sssp_bfs(void) {
220         splay_node_t *node, *to;
221         edge_t *e;
222         node_t *n;
223         list_t *todo_list;
224         list_node_t *from, *todonext;
225         bool indirect;
226
227         todo_list = list_alloc(NULL);
228
229         /* Clear visited status on nodes */
230
231         for(node = node_tree->head; node; node = node->next) {
232                 n = node->data;
233                 n->status.visited = false;
234                 n->status.indirect = true;
235                 n->distance = -1;
236         }
237
238         /* Begin with myself */
239
240         myself->status.visited = true;
241         myself->status.indirect = false;
242         myself->nexthop = myself;
243         myself->prevedge = NULL;
244         myself->via = myself;
245         myself->distance = 0;
246         list_insert_head(todo_list, myself);
247
248         /* Loop while todo_list is filled */
249
250         for(from = todo_list->head; from; from = todonext) {    /* "from" is the node from which we start */
251                 n = from->data;
252                 if(n->distance < 0)
253                         abort();
254
255                 for(to = n->edge_tree->head; to; to = to->next) {       /* "to" is the edge connected to "from" */
256                         e = to->data;
257
258                         if(!e->reverse)
259                                 continue;
260
261                         /* Situation:
262
263                                    /
264                                   /
265                            ----->(n)---e-->(e->to)
266                                   \
267                                    \
268
269                            Where e is an edge, (n) and (e->to) are nodes.
270                            n->address is set to the e->address of the edge left of n to n.
271                            We are currently examining the edge e right of n from n:
272
273                            - If edge e provides for better reachability of e->to, update
274                              e->to and (re)add it to the todo_list to (re)examine the reachability
275                              of nodes behind it.
276                          */
277
278                         indirect = n->status.indirect || e->options & OPTION_INDIRECT;
279
280                         if(e->to->status.visited
281                            && (!e->to->status.indirect || indirect)
282                            && (e->to->distance != n->distance + 1 || e->weight >= e->to->prevedge->weight))
283                                 continue;
284
285                         e->to->status.visited = true;
286                         e->to->status.indirect = indirect;
287                         e->to->nexthop = (n->nexthop == myself) ? e->to : n->nexthop;
288                         e->to->prevedge = e;
289                         e->to->via = indirect ? n->via : e->to;
290                         e->to->options = e->options;
291                         e->to->distance = n->distance + 1;
292
293                         if(e->to->address.sa.sa_family == AF_UNSPEC && e->address.sa.sa_family != AF_UNKNOWN)
294                                 update_node_udp(e->to, &e->address);
295
296                         list_insert_tail(todo_list, e->to);
297                 }
298
299                 todonext = from->next;
300                 list_delete_node(todo_list, from);
301         }
302
303         list_free(todo_list);
304 }
305
306 static void check_reachability(void) {
307         splay_node_t *node, *next;
308         node_t *n;
309         char *name;
310         char *address, *port;
311         char *envp[7];
312         int i;
313
314         /* Check reachability status. */
315
316         for(node = node_tree->head; node; node = next) {
317                 next = node->next;
318                 n = node->data;
319
320                 if(n->status.visited != n->status.reachable) {
321                         n->status.reachable = !n->status.reachable;
322
323                         if(n->status.reachable) {
324                                 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Node %s (%s) became reachable",
325                                            n->name, n->hostname);
326                         } else {
327                                 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Node %s (%s) became unreachable",
328                                            n->name, n->hostname);
329                         }
330
331                         /* TODO: only clear status.validkey if node is unreachable? */
332
333                         n->status.validkey = false;
334                         n->last_req_key = 0;
335
336                         n->maxmtu = MTU;
337                         n->minmtu = 0;
338                         n->mtuprobes = 0;
339
340                         if(timeout_initialized(&n->mtuevent))
341                                 event_del(&n->mtuevent);
342
343                         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
344                         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
345                         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
346                         xasprintf(&envp[3], "NODE=%s", n->name);
347                         sockaddr2str(&n->address, &address, &port);
348                         xasprintf(&envp[4], "REMOTEADDRESS=%s", address);
349                         xasprintf(&envp[5], "REMOTEPORT=%s", port);
350                         envp[6] = NULL;
351
352                         execute_script(n->status.reachable ? "host-up" : "host-down", envp);
353
354                         xasprintf(&name,
355                                          n->status.reachable ? "hosts/%s-up" : "hosts/%s-down",
356                                          n->name);
357                         execute_script(name, envp);
358
359                         free(name);
360                         free(address);
361                         free(port);
362
363                         for(i = 0; i < 6; i++)
364                                 free(envp[i]);
365
366                         subnet_update(n, NULL, n->status.reachable);
367
368                         if(!n->status.reachable)
369                                 update_node_udp(n, NULL);
370                         else if(n->connection)
371                                 send_ans_key(n);
372                 }
373         }
374 }
375
376 void graph(void) {
377         subnet_cache_flush();
378         sssp_bfs();
379         check_reachability();
380         mst_kruskal();
381 }