]> git.meshlink.io Git - meshlink/blob - src/net.c
cae8629881e79ec3d3ebd620b7feebf1e84ca57a
[meshlink] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2013 Guus Sliepen <guus@tinc-vpn.org>
5                   2006      Scott Lamb <slamb@slamb.org>
6                   2011      Loïc Grenié <loic.grenie@gmail.com>
7
8     This program is free software; you can redistribute it and/or modify
9     it under the terms of the GNU General Public License as published by
10     the Free Software Foundation; either version 2 of the License, or
11     (at your option) any later version.
12
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17
18     You should have received a copy of the GNU General Public License along
19     with this program; if not, write to the Free Software Foundation, Inc.,
20     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22
23 #include "system.h"
24
25 #include "utils.h"
26 #include "conf.h"
27 #include "connection.h"
28 #include "graph.h"
29 #include "logger.h"
30 #include "meta.h"
31 #include "net.h"
32 #include "netutl.h"
33 #include "protocol.h"
34 #include "xalloc.h"
35
36 int contradicting_add_edge = 0;
37 int contradicting_del_edge = 0;
38 static int sleeptime = 10;
39 time_t last_config_check = 0;
40 static timeout_t pingtimer;
41 static timeout_t periodictimer;
42
43 //TODO: move this to a better place
44 char *confbase;
45
46 /* Purge edges of unreachable nodes. Use carefully. */
47
48 // TODO: remove
49 void purge(void) {
50         logger(DEBUG_PROTOCOL, LOG_DEBUG, "Purging unreachable nodes");
51
52         /* Remove all edges owned by unreachable nodes. */
53
54         for splay_each(node_t, n, node_tree) {
55                 if(!n->status.reachable) {
56                         logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Purging node %s (%s)", n->name, n->hostname);
57
58                         for splay_each(edge_t, e, n->edge_tree) {
59                                 if(!tunnelserver)
60                                         send_del_edge(everyone, e);
61                                 edge_del(e);
62                         }
63                 }
64         }
65
66         /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
67
68         for splay_each(node_t, n, node_tree) {
69                 if(!n->status.reachable) {
70                         for splay_each(edge_t, e, edge_weight_tree)
71                                 if(e->to == n)
72                                         return;
73                 }
74         }
75 }
76
77 /*
78   Terminate a connection:
79   - Mark it as inactive
80   - Remove the edge representing this connection
81   - Kill it with fire
82   - Check if we need to retry making an outgoing connection
83 */
84 void terminate_connection(connection_t *c, bool report) {
85         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Closing connection with %s (%s)", c->name, c->hostname);
86
87         c->status.active = false;
88
89         if(c->node && c->node->connection == c)
90                 c->node->connection = NULL;
91
92         if(c->edge) {
93                 if(report && !tunnelserver)
94                         send_del_edge(everyone, c->edge);
95
96                 edge_del(c->edge);
97                 c->edge = NULL;
98
99                 /* Run MST and SSSP algorithms */
100
101                 graph();
102
103                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
104
105                 if(report && !c->node->status.reachable) {
106                         edge_t *e;
107                         e = lookup_edge(c->node, myself);
108                         if(e) {
109                                 if(!tunnelserver)
110                                         send_del_edge(everyone, e);
111                                 edge_del(e);
112                         }
113                 }
114         }
115
116         outgoing_t *outgoing = c->outgoing;
117         connection_del(c);
118
119         /* Check if this was our outgoing connection */
120
121         if(outgoing)
122                 do_outgoing_connection(outgoing);
123
124 #ifndef HAVE_MINGW
125         /* Clean up dead proxy processes */
126
127         while(waitpid(-1, NULL, WNOHANG) > 0);
128 #endif
129 }
130
131 /*
132   Check if the other end is active.
133   If we have sent packets, but didn't receive any,
134   then possibly the other end is dead. We send a
135   PING request over the meta connection. If the other
136   end does not reply in time, we consider them dead
137   and close the connection.
138 */
139 static void timeout_handler(void *data) {
140         for list_each(connection_t, c, connection_list) {
141                 if(c->last_ping_time + pingtimeout <= now.tv_sec) {
142                         if(c->status.active) {
143                                 if(c->status.pinged) {
144                                         logger(DEBUG_CONNECTIONS, LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds", c->name, c->hostname, (long)now.tv_sec - c->last_ping_time);
145                                 } else if(c->last_ping_time + pinginterval <= now.tv_sec) {
146                                         send_ping(c);
147                                         continue;
148                                 } else {
149                                         continue;
150                                 }
151                         } else {
152                                 if(c->status.connecting)
153                                         logger(DEBUG_CONNECTIONS, LOG_WARNING, "Timeout while connecting to %s (%s)", c->name, c->hostname);
154                                 else
155                                         logger(DEBUG_CONNECTIONS, LOG_WARNING, "Timeout from %s (%s) during authentication", c->name, c->hostname);
156                         }
157                         terminate_connection(c, c->status.active);
158                 }
159         }
160
161         timeout_set(data, &(struct timeval){pingtimeout, rand() % 100000});
162 }
163
164 static void periodic_handler(void *data) {
165         /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
166            This usually only happens when another node has the same Name as this node.
167            If so, sleep for a short while to prevent a storm of contradicting messages.
168         */
169
170         if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
171                 logger(DEBUG_ALWAYS, LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
172                 usleep(sleeptime * 1000000LL);
173                 sleeptime *= 2;
174                 if(sleeptime < 0)
175                         sleeptime = 3600;
176         } else {
177                 sleeptime /= 2;
178                 if(sleeptime < 10)
179                         sleeptime = 10;
180         }
181
182         contradicting_add_edge = 0;
183         contradicting_del_edge = 0;
184
185         /* If AutoConnect is set, check if we need to make or break connections. */
186
187         if(autoconnect && node_tree->count > 1) {
188                 /* Count number of active connections */
189                 int nc = 0;
190                 for list_each(connection_t, c, connection_list) {
191                         if(c->status.active)
192                                 nc++;
193                 }
194
195                 if(nc < autoconnect) {
196                         /* Not enough active connections, try to add one.
197                            Choose a random node, if we don't have a connection to it,
198                            and we are not already trying to make one, create an
199                            outgoing connection to this node.
200                         */
201                         int r = rand() % node_tree->count;
202                         int i = 0;
203
204                         for splay_each(node_t, n, node_tree) {
205                                 if(i++ != r)
206                                         continue;
207
208                                 if(n->connection)
209                                         break;
210
211                                 bool found = false;
212
213                                 for list_each(outgoing_t, outgoing, outgoing_list) {
214                                         if(!strcmp(outgoing->name, n->name)) {
215                                                 found = true;
216                                                 break;
217                                         }
218                                 }
219
220                                 if(!found) {
221                                         logger(DEBUG_CONNECTIONS, LOG_INFO, "Autoconnecting to %s", n->name);
222                                         outgoing_t *outgoing = xzalloc(sizeof *outgoing);
223                                         outgoing->name = xstrdup(n->name);
224                                         list_insert_tail(outgoing_list, outgoing);
225                                         setup_outgoing_connection(outgoing);
226                                 }
227                                 break;
228                         }
229                 } else if(nc > autoconnect) {
230                         /* Too many active connections, try to remove one.
231                            Choose a random outgoing connection to a node
232                            that has at least one other connection.
233                         */
234                         int r = rand() % nc;
235                         int i = 0;
236
237                         for list_each(connection_t, c, connection_list) {
238                                 if(!c->status.active)
239                                         continue;
240
241                                 if(i++ != r)
242                                         continue;
243
244                                 if(!c->outgoing || !c->node || c->node->edge_tree->count < 2)
245                                         break;
246
247                                 logger(DEBUG_CONNECTIONS, LOG_INFO, "Autodisconnecting from %s", c->name);
248                                 list_delete(outgoing_list, c->outgoing);
249                                 c->outgoing = NULL;
250                                 terminate_connection(c, c->status.active);
251                                 break;
252                         }
253                 }
254
255                 if(nc >= autoconnect) {
256                         /* If we have enough active connections,
257                            remove any pending outgoing connections.
258                         */
259                         for list_each(outgoing_t, o, outgoing_list) {
260                                 bool found = false;
261                                 for list_each(connection_t, c, connection_list) {
262                                         if(c->outgoing == o) {
263                                                 found = true;
264                                                 break;
265                                         }
266                                 }
267                                 if(!found) {
268                                         logger(DEBUG_CONNECTIONS, LOG_INFO, "Cancelled outgoing connection to %s", o->name);
269                                         list_delete_node(outgoing_list, node);
270                                 }
271                         }
272                 }
273         }
274
275         timeout_set(data, &(struct timeval){5, rand() % 100000});
276 }
277
278 void handle_meta_connection_data(connection_t *c) {
279         if (!receive_meta(c)) {
280                 terminate_connection(c, c->status.active);
281                 return;
282         }
283 }
284
285 #ifndef HAVE_MINGW
286 static void sigterm_handler(void *data) {
287         logger(DEBUG_ALWAYS, LOG_NOTICE, "Got %s signal", strsignal(((signal_t *)data)->signum));
288         event_exit();
289 }
290
291 static void sighup_handler(void *data) {
292         logger(DEBUG_ALWAYS, LOG_NOTICE, "Got %s signal", strsignal(((signal_t *)data)->signum));
293         if(reload_configuration())
294                 exit(1);
295 }
296
297 static void sigalrm_handler(void *data) {
298         logger(DEBUG_ALWAYS, LOG_NOTICE, "Got %s signal", strsignal(((signal_t *)data)->signum));
299         retry();
300 }
301 #endif
302
303 int reload_configuration(void) {
304         char *fname = NULL;
305
306         /* Reread our own configuration file */
307
308         exit_configuration(&config_tree);
309         init_configuration(&config_tree);
310
311         if(!read_server_config()) {
312                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to reread configuration file.");
313                 return EINVAL;
314         }
315
316         read_config_options(config_tree, NULL);
317
318         xasprintf(&fname, "%s" SLASH "hosts" SLASH "%s", confbase, myself->name);
319         read_config_file(config_tree, fname);
320         free(fname);
321
322         /* Parse some options that are allowed to be changed while tinc is running */
323
324         setup_myself_reloadable();
325
326         /* Try to make outgoing connections */
327
328         try_outgoing_connections();
329
330         /* Close connections to hosts that have a changed or deleted host config file */
331
332         for list_each(connection_t, c, connection_list) {
333                 xasprintf(&fname, "%s" SLASH "hosts" SLASH "%s", confbase, c->name);
334                 struct stat s;
335                 if(stat(fname, &s) || s.st_mtime > last_config_check) {
336                         logger(DEBUG_CONNECTIONS, LOG_INFO, "Host config file of %s has been changed", c->name);
337                         terminate_connection(c, c->status.active);
338                 }
339                 free(fname);
340         }
341
342         last_config_check = now.tv_sec;
343
344         return 0;
345 }
346
347 void retry(void) {
348         /* Reset the reconnection timers for all outgoing connections */
349         for list_each(outgoing_t, outgoing, outgoing_list) {
350                 outgoing->timeout = 0;
351                 if(outgoing->ev.cb)
352                         timeout_set(&outgoing->ev, &(struct timeval){0, 0});
353         }
354
355         /* Check for outgoing connections that are in progress, and reset their ping timers */
356         for list_each(connection_t, c, connection_list) {
357                 if(c->outgoing && !c->node)
358                         c->last_ping_time = 0;
359         }
360
361         /* Kick the ping timeout handler */
362         timeout_set(&pingtimer, &(struct timeval){0, 0});
363 }
364
365 /*
366   this is where it all happens...
367 */
368 int main_loop(void) {
369         timeout_add(&pingtimer, timeout_handler, &pingtimer, &(struct timeval){pingtimeout, rand() % 100000});
370         timeout_add(&periodictimer, periodic_handler, &periodictimer, &(struct timeval){pingtimeout, rand() % 100000});
371
372 #ifndef HAVE_MINGW
373         signal_t sighup = {0};
374         signal_t sigterm = {0};
375         signal_t sigquit = {0};
376         signal_t sigint = {0};
377         signal_t sigalrm = {0};
378
379         signal_add(&sighup, sighup_handler, &sighup, SIGHUP);
380         signal_add(&sigterm, sigterm_handler, &sigterm, SIGTERM);
381         signal_add(&sigquit, sigterm_handler, &sigquit, SIGQUIT);
382         signal_add(&sigint, sigterm_handler, &sigint, SIGINT);
383         signal_add(&sigalrm, sigalrm_handler, &sigalrm, SIGALRM);
384 #endif
385
386         if(!event_loop()) {
387                 logger(DEBUG_ALWAYS, LOG_ERR, "Error while waiting for input: %s", strerror(errno));
388                 return 1;
389         }
390
391 #ifndef HAVE_MINGW
392         signal_del(&sighup);
393         signal_del(&sigterm);
394         signal_del(&sigquit);
395         signal_del(&sigint);
396         signal_del(&sigalrm);
397 #endif
398
399         timeout_del(&periodictimer);
400         timeout_del(&pingtimer);
401
402         return 0;
403 }