]> git.meshlink.io Git - meshlink-tiny/blob - src/net.c
Remove all support for channels.
[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->status.active && c->last_key_renewal + 3600 < mesh->loop.now.tv_sec) {
105                         devtool_sptps_renewal_probe((meshlink_node_t *)c->node);
106
107                         if(!sptps_force_kex(&c->sptps)) {
108                                 logger(mesh, MESHLINK_ERROR, "SPTPS key renewal for connection with %s failed", c->name);
109                                 terminate_connection(mesh, c, true);
110                                 continue;
111                         } else {
112                                 c->last_key_renewal = mesh->loop.now.tv_sec;
113                         }
114                 }
115
116                 if(c->last_ping_time + pingtimeout < mesh->loop.now.tv_sec) {
117                         if(c->status.active) {
118                                 if(c->status.pinged) {
119                                         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);
120                                 } else if(c->last_ping_time + pinginterval <= mesh->loop.now.tv_sec) {
121                                         send_ping(mesh, c);
122                                         continue;
123                                 } else {
124                                         continue;
125                                 }
126                         } else {
127                                 if(c->status.connecting) {
128                                         logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
129                                 } else {
130                                         logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
131                                 }
132                         }
133
134                         terminate_connection(mesh, c, c->status.active);
135                 }
136         }
137
138         timeout_set(&mesh->loop, data, &(struct timespec) {
139                 1, prng(mesh, TIMER_FUDGE)
140         });
141 }
142
143 static void periodic_handler(event_loop_t *loop, void *data) {
144         meshlink_handle_t *mesh = loop->data;
145
146         /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
147            This usually only happens when another node has the same Name as this node.
148            If so, sleep for a short while to prevent a storm of contradicting messages.
149         */
150
151         if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
152                 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
153                 struct timespec ts = {mesh->sleeptime, 0};
154                 nanosleep(&ts, NULL);
155                 mesh->sleeptime *= 2;
156
157                 if(mesh->sleeptime < 0) {
158                         mesh->sleeptime = 3600;
159                 }
160         } else {
161                 mesh->sleeptime /= 2;
162
163                 if(mesh->sleeptime < 10) {
164                         mesh->sleeptime = 10;
165                 }
166         }
167
168         mesh->contradicting_add_edge = 0;
169         mesh->contradicting_del_edge = 0;
170
171         int timeout = default_timeout;
172
173         /* Check if we need to make or break connections. */
174
175         if(mesh->peer && !mesh->connection && !mesh->outgoing) {
176                 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", mesh->peer->name);
177                 mesh->outgoing = xzalloc(sizeof(outgoing_t));
178                 mesh->outgoing->node = mesh->peer;
179                 setup_outgoing_connection(mesh, mesh->outgoing);
180         }
181
182         for(node_t *n = mesh->peer; n; n = NULL) {
183                 if(n->status.dirty) {
184                         if(!node_write_config(mesh, n, false)) {
185                                 logger(mesh, MESHLINK_DEBUG, "Could not update %s", n->name);
186                         }
187                 }
188         }
189
190         timeout_set(&mesh->loop, data, &(struct timespec) {
191                 timeout, prng(mesh, TIMER_FUDGE)
192         });
193 }
194
195 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
196         if(!receive_meta(mesh, c)) {
197                 terminate_connection(mesh, c, c->status.active);
198                 return;
199         }
200 }
201
202 void retry(meshlink_handle_t *mesh) {
203         /* Reset the reconnection timers for all outgoing connections */
204         for(outgoing_t *outgoing = mesh->outgoing; outgoing; outgoing = NULL) {
205                 outgoing->timeout = 0;
206
207                 if(outgoing->ev.cb) {
208                         timeout_set(&mesh->loop, &outgoing->ev, &(struct timespec) {
209                                 0, 0
210                         });
211                 }
212         }
213
214         /* For active connections, check if their addresses are still valid.
215          * If yes, reset their ping timers, otherwise terminate them. */
216         for(connection_t *c = mesh->connection; c; c = NULL) {
217                 if(!c->status.active) {
218                         continue;
219                 }
220
221                 if(!c->status.pinged) {
222                         c->last_ping_time = -3600;
223                 }
224
225                 sockaddr_t sa;
226                 socklen_t salen = sizeof(sa);
227
228                 if(getsockname(c->socket, &sa.sa, &salen)) {
229                         continue;
230                 }
231
232                 switch(sa.sa.sa_family) {
233                 case AF_INET:
234                         sa.in.sin_port = 0;
235                         break;
236
237                 case AF_INET6:
238                         sa.in6.sin6_port = 0;
239                         break;
240
241                 default:
242                         continue;
243                 }
244
245                 int sock = socket(sa.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
246
247                 if(sock == -1) {
248                         continue;
249                 }
250
251                 if(bind(sock, &sa.sa, salen) && errno == EADDRNOTAVAIL) {
252                         logger(mesh, MESHLINK_DEBUG, "Local address for connection to %s no longer valid, terminating", c->name);
253                         terminate_connection(mesh, c, c->status.active);
254                 }
255
256                 closesocket(sock);
257         }
258
259         /* Kick the ping timeout handler */
260         if(mesh->pingtimer.cb) {
261                 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timespec) {
262                         0, 0
263                 });
264         }
265 }
266
267 /*
268   this is where it all happens...
269 */
270 void main_loop(meshlink_handle_t *mesh) {
271         timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timespec) {
272                 1, prng(mesh, TIMER_FUDGE)
273         });
274         timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timespec) {
275                 0, 0
276         });
277
278         //Add signal handler
279         mesh->datafromapp.signum = 0;
280         signal_add(&mesh->loop, &mesh->datafromapp, meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
281
282         if(!event_loop_run(&mesh->loop, mesh)) {
283                 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
284                 call_error_cb(mesh, MESHLINK_ENETWORK);
285         }
286
287         signal_del(&mesh->loop, &mesh->datafromapp);
288         timeout_del(&mesh->loop, &mesh->periodictimer);
289         timeout_del(&mesh->loop, &mesh->pingtimer);
290 }