1725241157b435f7a6a78c9686004ac5d8f03e7e
[tinc] / src / graph.c
1 /*
2     graph.c -- graph algorithms
3     Copyright (C) 2001-2011 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         ifdebug(SCARY_THINGS) logger(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                 ifdebug(SCARY_THINGS) logger(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         ifdebug(SCARY_THINGS) logger(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                         ifdebug(SCARY_THINGS) logger(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         }
236
237         /* Begin with myself */
238
239         myself->status.visited = true;
240         myself->status.indirect = false;
241         myself->nexthop = myself;
242         myself->prevedge = NULL;
243         myself->via = myself;
244         list_insert_head(todo_list, myself);
245
246         /* Loop while todo_list is filled */
247
248         for(from = todo_list->head; from; from = todonext) {    /* "from" is the node from which we start */
249                 n = from->data;
250
251                 for(to = n->edge_tree->head; to; to = to->next) {       /* "to" is the edge connected to "from" */
252                         e = to->data;
253
254                         if(!e->reverse)
255                                 continue;
256
257                         /* Situation:
258
259                                    /
260                                   /
261                            ----->(n)---e-->(e->to)
262                                   \
263                                    \
264
265                            Where e is an edge, (n) and (e->to) are nodes.
266                            n->address is set to the e->address of the edge left of n to n.
267                            We are currently examining the edge e right of n from n:
268
269                            - If edge e provides for better reachability of e->to, update
270                              e->to and (re)add it to the todo_list to (re)examine the reachability
271                              of nodes behind it.
272                          */
273
274                         indirect = n->status.indirect || e->options & OPTION_INDIRECT;
275
276                         if(e->to->status.visited
277                            && (!e->to->status.indirect || indirect))
278                                 continue;
279
280                         e->to->status.visited = true;
281                         e->to->status.indirect = indirect;
282                         e->to->nexthop = (n->nexthop == myself) ? e->to : n->nexthop;
283                         e->to->prevedge = e;
284                         e->to->via = indirect ? n->via : e->to;
285                         e->to->options = e->options;
286
287                         if(e->to->address.sa.sa_family == AF_UNSPEC && e->address.sa.sa_family != AF_UNKNOWN)
288                                 update_node_udp(e->to, &e->address);
289
290                         list_insert_tail(todo_list, e->to);
291                 }
292
293                 todonext = from->next;
294                 list_delete_node(todo_list, from);
295         }
296
297         list_free(todo_list);
298 }
299
300 static void check_reachability(void) {
301         splay_node_t *node, *next;
302         node_t *n;
303         char *name;
304         char *address, *port;
305         char *envp[7];
306         int i;
307
308         /* Check reachability status. */
309
310         for(node = node_tree->head; node; node = next) {
311                 next = node->next;
312                 n = node->data;
313
314                 if(n->status.visited != n->status.reachable) {
315                         n->status.reachable = !n->status.reachable;
316
317                         if(n->status.reachable) {
318                                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Node %s (%s) became reachable",
319                                            n->name, n->hostname);
320                         } else {
321                                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Node %s (%s) became unreachable",
322                                            n->name, n->hostname);
323                         }
324
325                         /* TODO: only clear status.validkey if node is unreachable? */
326
327                         n->status.validkey = false;
328                         n->last_req_key = 0;
329
330                         n->maxmtu = MTU;
331                         n->minmtu = 0;
332                         n->mtuprobes = 0;
333
334                         if(timeout_initialized(&n->mtuevent))
335                                 event_del(&n->mtuevent);
336
337                         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
338                         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
339                         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
340                         xasprintf(&envp[3], "NODE=%s", n->name);
341                         sockaddr2str(&n->address, &address, &port);
342                         xasprintf(&envp[4], "REMOTEADDRESS=%s", address);
343                         xasprintf(&envp[5], "REMOTEPORT=%s", port);
344                         envp[6] = NULL;
345
346                         execute_script(n->status.reachable ? "host-up" : "host-down", envp);
347
348                         xasprintf(&name,
349                                          n->status.reachable ? "hosts/%s-up" : "hosts/%s-down",
350                                          n->name);
351                         execute_script(name, envp);
352
353                         free(name);
354                         free(address);
355                         free(port);
356
357                         for(i = 0; i < 6; i++)
358                                 free(envp[i]);
359
360                         subnet_update(n, NULL, n->status.reachable);
361
362                         if(!n->status.reachable)
363                                 update_node_udp(n, NULL);
364                         else if(n->connection)
365                                 send_ans_key(n);
366                 }
367         }
368 }
369
370 void graph(void) {
371         subnet_cache_flush();
372         sssp_bfs();
373         check_reachability();
374         mst_kruskal();
375 }