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