]> git.meshlink.io Git - meshlink/blob - src/net.c
Improve the autoconnect algorithm.
[meshlink] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 2014-2017 Guus Sliepen <guus@meshlink.io>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include "autoconnect.h"
23 #include "conf.h"
24 #include "connection.h"
25 #include "graph.h"
26 #include "logger.h"
27 #include "meshlink_internal.h"
28 #include "meta.h"
29 #include "net.h"
30 #include "netutl.h"
31 #include "protocol.h"
32 #include "utils.h"
33 #include "xalloc.h"
34
35 #include <assert.h>
36
37 #if !defined(min)
38 static inline int min(int a, int b) {
39         return a < b ? a : b;
40 }
41 #endif
42
43 static const int default_timeout = 5;
44
45 /*
46   Terminate a connection:
47   - Mark it as inactive
48   - Remove the edge representing this connection
49   - Kill it with fire
50   - Check if we need to retry making an outgoing connection
51 */
52 void terminate_connection(meshlink_handle_t *mesh, connection_t *c, bool report) {
53         logger(mesh, MESHLINK_INFO, "Closing connection with %s", c->name);
54
55         c->status.active = false;
56
57         if(c->node && c->node->connection == c) {
58                 c->node->connection = NULL;
59         }
60
61         if(c->edge) {
62                 if(report) {
63                         send_del_edge(mesh, mesh->everyone, c->edge, 0);
64                 }
65
66                 edge_del(mesh, c->edge);
67                 c->edge = NULL;
68
69                 /* Run MST and SSSP algorithms */
70
71                 graph(mesh);
72
73                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
74
75                 if(report && c->node && !c->node->status.reachable) {
76                         edge_t *e;
77                         e = lookup_edge(c->node, mesh->self);
78
79                         if(e) {
80                                 send_del_edge(mesh, mesh->everyone, e, 0);
81                                 edge_del(mesh, e);
82                         }
83                 }
84         }
85
86         outgoing_t *outgoing = c->outgoing;
87         connection_del(mesh, c);
88
89         /* Check if this was our outgoing connection */
90
91         if(outgoing) {
92                 do_outgoing_connection(mesh, outgoing);
93         }
94
95 #ifndef HAVE_MINGW
96         /* Clean up dead proxy processes */
97
98         while(waitpid(-1, NULL, WNOHANG) > 0);
99
100 #endif
101 }
102
103 /*
104   Check if the other end is active.
105   If we have sent packets, but didn't receive any,
106   then possibly the other end is dead. We send a
107   PING request over the meta connection. If the other
108   end does not reply in time, we consider them dead
109   and close the connection.
110 */
111 static void timeout_handler(event_loop_t *loop, void *data) {
112         meshlink_handle_t *mesh = loop->data;
113         logger(mesh, MESHLINK_DEBUG, "timeout_handler()");
114
115         for list_each(connection_t, c, mesh->connections) {
116                 int pingtimeout = c->node ? mesh->dev_class_traits[c->node->devclass].pingtimeout : default_timeout;
117
118                 // Also make sure that if outstanding key requests for the UDP counterpart of a connection has timed out, we restart it.
119                 if(c->node) {
120                         if(c->node->status.waitingforkey && c->node->last_req_key + pingtimeout <= mesh->loop.now.tv_sec) {
121                                 send_req_key(mesh, c->node);
122                         }
123                 }
124
125                 if(c->last_ping_time + pingtimeout <= mesh->loop.now.tv_sec) {
126                         if(c->status.active) {
127                                 if(c->status.pinged) {
128                                         logger(mesh, MESHLINK_INFO, "%s didn't respond to PING in %ld seconds", c->name, (long)mesh->loop.now.tv_sec - c->last_ping_time);
129                                 } else if(c->last_ping_time + mesh->dev_class_traits[c->node->devclass].pinginterval <= mesh->loop.now.tv_sec) {
130                                         send_ping(mesh, c);
131                                         continue;
132                                 } else {
133                                         continue;
134                                 }
135                         } else {
136                                 if(c->status.connecting) {
137                                         logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
138                                 } else {
139                                         logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
140                                 }
141                         }
142
143                         terminate_connection(mesh, c, c->status.active);
144                 }
145         }
146
147         timeout_set(&mesh->loop, data, &(struct timeval) {
148                 default_timeout, rand() % 100000
149         });
150 }
151
152 static void periodic_handler(event_loop_t *loop, void *data) {
153         meshlink_handle_t *mesh = loop->data;
154
155         /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
156            This usually only happens when another node has the same Name as this node.
157            If so, sleep for a short while to prevent a storm of contradicting messages.
158         */
159
160         if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
161                 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
162                 usleep(mesh->sleeptime * 1000000LL);
163                 mesh->sleeptime *= 2;
164
165                 if(mesh->sleeptime < 0) {
166                         mesh->sleeptime = 3600;
167                 }
168         } else {
169                 mesh->sleeptime /= 2;
170
171                 if(mesh->sleeptime < 10) {
172                         mesh->sleeptime = 10;
173                 }
174         }
175
176         mesh->contradicting_add_edge = 0;
177         mesh->contradicting_del_edge = 0;
178
179         int timeout = default_timeout;
180
181         /* Check if we need to make or break connections. */
182
183         if(mesh->nodes->count > 1) {
184                 unsigned int cur_connects = do_autoconnect(mesh);
185
186                 // reduce timeout if we don't have enough connections + outgoings
187                 if (cur_connects + mesh->outgoings->count < 3) {
188                         timeout = 1;
189                 }
190         }
191
192         /* Write dirty config files out to disk */
193
194         for splay_each(node_t, n, mesh->nodes) {
195                 if(n->status.dirty) {
196                         node_write_config(mesh, n);
197                         n->status.dirty = false;
198                 }
199         }
200
201         timeout_set(&mesh->loop, data, &(struct timeval) {
202                 timeout, rand() % 100000
203         });
204 }
205
206 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
207         if(!receive_meta(mesh, c)) {
208                 terminate_connection(mesh, c, c->status.active);
209                 return;
210         }
211 }
212
213 void retry(meshlink_handle_t *mesh) {
214         /* Reset the reconnection timers for all outgoing connections */
215         for list_each(outgoing_t, outgoing, mesh->outgoings) {
216                 outgoing->timeout = 0;
217
218                 if(outgoing->ev.cb)
219                         timeout_set(&mesh->loop, &outgoing->ev, &(struct timeval) {
220                         0, 0
221                 });
222         }
223
224 #ifdef HAVE_IFADDRS_H
225         struct ifaddrs *ifa = NULL;
226         getifaddrs(&ifa);
227 #endif
228
229         /* For active connections, check if their addresses are still valid.
230          * If yes, reset their ping timers, otherwise terminate them. */
231         for list_each(connection_t, c, mesh->connections) {
232                 if(!c->status.active) {
233                         continue;
234                 }
235
236                 if(!c->status.pinged) {
237                         c->last_ping_time = 0;
238                 }
239
240 #ifdef HAVE_IFADDRS_H
241
242                 if(!ifa) {
243                         continue;
244                 }
245
246                 sockaddr_t sa;
247                 socklen_t salen = sizeof(sa);
248
249                 if(getsockname(c->socket, &sa.sa, &salen)) {
250                         continue;
251                 }
252
253                 bool found = false;
254
255                 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
256                         if(ifap->ifa_addr && !sockaddrcmp_noport(&sa, (sockaddr_t *)ifap->ifa_addr)) {
257                                 found = true;
258                                 break;
259                         }
260
261                 }
262
263                 if(!found) {
264                         logger(mesh, MESHLINK_DEBUG, "Local address for connection to %s no longer valid, terminating", c->name);
265                         terminate_connection(mesh, c, c->status.active);
266                 }
267
268 #endif
269         }
270
271 #ifdef HAVE_IFADDRS_H
272
273         if(ifa) {
274                 freeifaddrs(ifa);
275         }
276
277 #endif
278
279         /* Kick the ping timeout handler */
280         timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timeval) {
281                 0, 0
282         });
283 }
284
285 /*
286   this is where it all happens...
287 */
288 int main_loop(meshlink_handle_t *mesh) {
289         timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timeval) {
290                 default_timeout, rand() % 100000
291         });
292         timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timeval) {
293                 0, 0
294         });
295
296         //Add signal handler
297         mesh->datafromapp.signum = 0;
298         signal_add(&(mesh->loop), &(mesh->datafromapp), (signal_cb_t)meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
299
300         if(!event_loop_run(&(mesh->loop), &(mesh->mesh_mutex))) {
301                 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
302                 abort();
303                 timeout_del(&mesh->loop, &mesh->periodictimer);
304                 timeout_del(&mesh->loop, &mesh->pingtimer);
305
306                 return 1;
307         }
308
309         timeout_del(&mesh->loop, &mesh->periodictimer);
310         timeout_del(&mesh->loop, &mesh->pingtimer);
311
312         return 0;
313 }