]> git.meshlink.io Git - meshlink-tiny/blob - src/net.c
101c95792dc3eb76476205a85dd3f68bd0b149b7
[meshlink-tiny] / 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 "utils.h"
23 #include "conf.h"
24 #include "connection.h"
25 #include "devtools.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 "sptps.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 static const int default_interval = 60;
45
46 /*
47   Terminate a connection:
48   - Mark it as inactive
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         (void)report;
54
55         if(c->status.active) {
56                 logger(mesh, MESHLINK_INFO, "Closing connection with %s", c->name);
57         }
58
59         if(c->node && c->node->connection == c) {
60                 if(c->status.active && mesh->meta_status_cb) {
61                         mesh->meta_status_cb(mesh, (meshlink_node_t *)c->node, false);
62                 }
63
64                 c->node->connection = NULL;
65                 c->node->status.reachable = false;
66                 update_node_status(mesh, c->node);
67         }
68
69         c->status.active = false;
70
71         outgoing_t *outgoing = c->outgoing;
72         connection_del(mesh, c);
73
74         /* Check if this was our outgoing connection */
75
76         if(outgoing) {
77                 do_outgoing_connection(mesh, outgoing);
78         }
79 }
80
81 /*
82   Check if the other end is active.
83   If we have sent packets, but didn't receive any,
84   then possibly the other end is dead. We send a
85   PING request over the meta connection. If the other
86   end does not reply in time, we consider them dead
87   and close the connection.
88 */
89 static void timeout_handler(event_loop_t *loop, void *data) {
90         assert(data);
91
92         meshlink_handle_t *mesh = loop->data;
93         logger(mesh, MESHLINK_DEBUG, "timeout_handler()");
94
95         for(connection_t *c = mesh->connection; c; c = NULL) {
96                 int pingtimeout = c->node ? mesh->dev_class_traits[c->node->devclass].pingtimeout : default_timeout;
97                 int pinginterval = c->node ? mesh->dev_class_traits[c->node->devclass].pinginterval : default_interval;
98
99                 if(c->outgoing && !c->status.active && c->outgoing->timeout < 5) {
100                         pingtimeout = 1;
101                 }
102
103                 // Also make sure that if outstanding key requests for the UDP counterpart of a connection has timed out, we restart it.
104                 if(c->node) {
105                         if(c->node->status.waitingforkey && c->node->last_req_key + pingtimeout < mesh->loop.now.tv_sec) {
106                                 send_req_key(mesh, c->node);
107                         }
108                 }
109
110                 if(c->status.active && c->last_key_renewal + 3600 < mesh->loop.now.tv_sec) {
111                         devtool_sptps_renewal_probe((meshlink_node_t *)c->node);
112
113                         if(!sptps_force_kex(&c->sptps)) {
114                                 logger(mesh, MESHLINK_ERROR, "SPTPS key renewal for connection with %s failed", c->name);
115                                 terminate_connection(mesh, c, true);
116                                 continue;
117                         } else {
118                                 c->last_key_renewal = mesh->loop.now.tv_sec;
119                         }
120                 }
121
122                 if(c->last_ping_time + pingtimeout < mesh->loop.now.tv_sec) {
123                         if(c->status.active) {
124                                 if(c->status.pinged) {
125                                         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);
126                                 } else if(c->last_ping_time + pinginterval <= mesh->loop.now.tv_sec) {
127                                         send_ping(mesh, c);
128                                         continue;
129                                 } else {
130                                         continue;
131                                 }
132                         } else {
133                                 if(c->status.connecting) {
134                                         logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
135                                 } else {
136                                         logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
137                                 }
138                         }
139
140                         terminate_connection(mesh, c, c->status.active);
141                 }
142         }
143
144         timeout_set(&mesh->loop, data, &(struct timespec) {
145                 1, prng(mesh, TIMER_FUDGE)
146         });
147 }
148
149 static void periodic_handler(event_loop_t *loop, void *data) {
150         meshlink_handle_t *mesh = loop->data;
151
152         /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
153            This usually only happens when another node has the same Name as this node.
154            If so, sleep for a short while to prevent a storm of contradicting messages.
155         */
156
157         if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
158                 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
159                 struct timespec ts = {mesh->sleeptime, 0};
160                 nanosleep(&ts, NULL);
161                 mesh->sleeptime *= 2;
162
163                 if(mesh->sleeptime < 0) {
164                         mesh->sleeptime = 3600;
165                 }
166         } else {
167                 mesh->sleeptime /= 2;
168
169                 if(mesh->sleeptime < 10) {
170                         mesh->sleeptime = 10;
171                 }
172         }
173
174         mesh->contradicting_add_edge = 0;
175         mesh->contradicting_del_edge = 0;
176
177         int timeout = default_timeout;
178
179         /* Check if we need to make or break connections. */
180
181         if(mesh->peer && !mesh->connection && !mesh->outgoing) {
182                 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", mesh->peer->name);
183                 mesh->outgoing = xzalloc(sizeof(outgoing_t));
184                 mesh->outgoing->node = mesh->peer;
185                 setup_outgoing_connection(mesh, mesh->outgoing);
186         }
187
188         for(node_t *n = mesh->peer; n; n = NULL) {
189                 if(n->status.dirty) {
190                         if(!node_write_config(mesh, n, false)) {
191                                 logger(mesh, MESHLINK_DEBUG, "Could not update %s", n->name);
192                         }
193                 }
194
195                 if(n->status.reachable && n->status.validkey && n->last_req_key + 3600 < mesh->loop.now.tv_sec) {
196                         logger(mesh, MESHLINK_DEBUG, "SPTPS key renewal for node %s", n->name);
197                         devtool_sptps_renewal_probe((meshlink_node_t *)n);
198
199                         if(!sptps_force_kex(&n->sptps)) {
200                                 logger(mesh, MESHLINK_ERROR, "SPTPS key renewal for node %s failed", n->name);
201                                 n->status.validkey = false;
202                                 sptps_stop(&n->sptps);
203                                 n->status.waitingforkey = false;
204                                 n->last_req_key = -3600;
205                         } else {
206                                 n->last_req_key = mesh->loop.now.tv_sec;
207                         }
208                 }
209         }
210
211         timeout_set(&mesh->loop, data, &(struct timespec) {
212                 timeout, prng(mesh, TIMER_FUDGE)
213         });
214 }
215
216 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
217         if(!receive_meta(mesh, c)) {
218                 terminate_connection(mesh, c, c->status.active);
219                 return;
220         }
221 }
222
223 void retry(meshlink_handle_t *mesh) {
224         /* Reset the reconnection timers for all outgoing connections */
225         for(outgoing_t *outgoing = mesh->outgoing; outgoing; outgoing = NULL) {
226                 outgoing->timeout = 0;
227
228                 if(outgoing->ev.cb) {
229                         timeout_set(&mesh->loop, &outgoing->ev, &(struct timespec) {
230                                 0, 0
231                         });
232                 }
233         }
234
235         /* For active connections, check if their addresses are still valid.
236          * If yes, reset their ping timers, otherwise terminate them. */
237         for(connection_t *c = mesh->connection; c; c = NULL) {
238                 if(!c->status.active) {
239                         continue;
240                 }
241
242                 if(!c->status.pinged) {
243                         c->last_ping_time = -3600;
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                 switch(sa.sa.sa_family) {
254                 case AF_INET:
255                         sa.in.sin_port = 0;
256                         break;
257
258                 case AF_INET6:
259                         sa.in6.sin6_port = 0;
260                         break;
261
262                 default:
263                         continue;
264                 }
265
266                 int sock = socket(sa.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
267
268                 if(sock == -1) {
269                         continue;
270                 }
271
272                 if(bind(sock, &sa.sa, salen) && errno == EADDRNOTAVAIL) {
273                         logger(mesh, MESHLINK_DEBUG, "Local address for connection to %s no longer valid, terminating", c->name);
274                         terminate_connection(mesh, c, c->status.active);
275                 }
276
277                 closesocket(sock);
278         }
279
280         /* Kick the ping timeout handler */
281         if(mesh->pingtimer.cb) {
282                 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timespec) {
283                         0, 0
284                 });
285         }
286 }
287
288 /*
289   this is where it all happens...
290 */
291 void main_loop(meshlink_handle_t *mesh) {
292         timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timespec) {
293                 1, prng(mesh, TIMER_FUDGE)
294         });
295         timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timespec) {
296                 0, 0
297         });
298
299         //Add signal handler
300         mesh->datafromapp.signum = 0;
301         signal_add(&mesh->loop, &mesh->datafromapp, meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
302
303         if(!event_loop_run(&mesh->loop, mesh)) {
304                 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
305                 call_error_cb(mesh, MESHLINK_ENETWORK);
306         }
307
308         signal_del(&mesh->loop, &mesh->datafromapp);
309         timeout_del(&mesh->loop, &mesh->periodictimer);
310         timeout_del(&mesh->loop, &mesh->pingtimer);
311 }