]> git.meshlink.io Git - meshlink/blob - src/net.c
Merge branch 'discovery' into everbase
[meshlink] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 2014 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 "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 "xalloc.h"
33
34 static const int min(int a, int b) {
35         return a < b ? a : b;
36 }
37
38 /*
39   Terminate a connection:
40   - Mark it as inactive
41   - Remove the edge representing this connection
42   - Kill it with fire
43   - Check if we need to retry making an outgoing connection
44 */
45 void terminate_connection(meshlink_handle_t *mesh, connection_t *c, bool report) {
46         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Closing connection with %s (%s)", c->name, c->hostname);
47
48         c->status.active = false;
49
50         if(c->node && c->node->connection == c)
51                 c->node->connection = NULL;
52
53         if(c->edge) {
54                 if(report)
55                         send_del_edge(mesh, mesh->everyone, c->edge);
56
57                 edge_del(mesh, c->edge);
58                 c->edge = NULL;
59
60                 /* Run MST and SSSP algorithms */
61
62                 graph(mesh);
63
64                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
65
66                 if(report && !c->node->status.reachable) {
67                         edge_t *e;
68                         e = lookup_edge(c->node, mesh->self);
69                         if(e) {
70                                 send_del_edge(mesh, mesh->everyone, e);
71                                 edge_del(mesh, e);
72                         }
73                 }
74         }
75
76         outgoing_t *outgoing = c->outgoing;
77         connection_del(mesh, c);
78
79         /* Check if this was our outgoing connection */
80
81         if(outgoing)
82                 do_outgoing_connection(mesh, outgoing);
83
84 #ifndef HAVE_MINGW
85         /* Clean up dead proxy processes */
86
87         while(waitpid(-1, NULL, WNOHANG) > 0);
88 #endif
89 }
90
91 /*
92   Check if the other end is active.
93   If we have sent packets, but didn't receive any,
94   then possibly the other end is dead. We send a
95   PING request over the meta connection. If the other
96   end does not reply in time, we consider them dead
97   and close the connection.
98 */
99 static void timeout_handler(event_loop_t *loop, void *data) {
100         meshlink_handle_t *mesh = loop->data;
101
102         for list_each(connection_t, c, mesh->connections) {
103                 if(c->last_ping_time + mesh->pingtimeout <= mesh->loop.now.tv_sec) {
104                         if(c->status.active) {
105                                 if(c->status.pinged) {
106                                         logger(DEBUG_CONNECTIONS, LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds", c->name, c->hostname, (long)mesh->loop.now.tv_sec - c->last_ping_time);
107                                 } else if(c->last_ping_time + mesh->pinginterval <= mesh->loop.now.tv_sec) {
108                                         send_ping(mesh, c);
109                                         continue;
110                                 } else {
111                                         continue;
112                                 }
113                         } else {
114                                 if(c->status.connecting)
115                                         logger(DEBUG_CONNECTIONS, LOG_WARNING, "Timeout while connecting to %s (%s)", c->name, c->hostname);
116                                 else
117                                         logger(DEBUG_CONNECTIONS, LOG_WARNING, "Timeout from %s (%s) during authentication", c->name, c->hostname);
118                         }
119                         terminate_connection(mesh, c, c->status.active);
120                 }
121         }
122
123         timeout_set(&mesh->loop, data, &(struct timeval){mesh->pingtimeout, rand() % 100000});
124 }
125
126 /// Utility function to establish connections based on condition check
127 /** The function iterates over all nodes, but skips those that do
128  *  not pass the condition check.
129  *  
130  *  The condition check function is passed
131  *  a pointer to a random number r between 0 and rand_modulo, a pointer to the
132  *  current node index i, and the node pointer n. This function should return true
133  *  if a connection attempt to the node should be made.
134  *  
135  *  @param mesh         A pointer to the mesh structure
136  *  @param rand_modulo  Random index is selected between 0 and rand_modulo
137  *  @cond_check         A function pointer. This function should return true
138  *                      if a connection attempt to the node should be made
139  */
140 static void cond_add_connection(meshlink_handle_t *mesh, int rand_modulo, bool (*cond_check)(int*, int*, node_t*)) {
141         int r = rand() % rand_modulo;
142         int i = 0;
143
144         for splay_each(node_t, n, mesh->nodes) {
145                 /* skip nodes that do not pass condition check */
146                 if(!(*cond_check)(&i, &r, n))
147                         continue;
148
149                 /* check if there is already a connection attempt to this node */
150                 bool found = false;
151                 for list_each(outgoing_t, outgoing, mesh->outgoings) {
152                         if(!strcmp(outgoing->name, n->name)) {
153                                 found = true;
154                                 break;
155                         }
156                 }
157
158                 if(!found) {
159                         //TODO: if the node is blacklisted the connection will not happen, but
160                         //the user will read this debug message "Autoconnecting to %s" that is misleading
161                         logger(DEBUG_CONNECTIONS, LOG_INFO, "Autoconnecting to %s", n->name);
162                         outgoing_t *outgoing = xzalloc(sizeof *outgoing);
163                         outgoing->mesh = mesh;
164                         outgoing->name = xstrdup(n->name);
165                         list_insert_tail(mesh->outgoings, outgoing);
166                         setup_outgoing_connection(mesh, outgoing);
167                 }
168                 break;
169         }
170 }
171
172 static bool found_random_node(int *i, int *r, node_t *n) {
173         if((*i)++ != *r)
174                 return false;
175
176         if(n->connection)
177                 return false;
178         
179         return true;
180 }
181
182 static bool found_random_unreachable_node(int *i, int *r, node_t *n) {
183         if(n->status.reachable)
184                 return false;
185         
186         if((*i)++ != *r)
187                 return false;
188
189         if(n->connection)
190                 return false;
191
192         return true;
193 }
194
195 static void periodic_handler(event_loop_t *loop, void *data) {
196         meshlink_handle_t *mesh = loop->data;
197
198         /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
199            This usually only happens when another node has the same Name as this node.
200            If so, sleep for a short while to prevent a storm of contradicting messages.
201         */
202
203         if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
204                 logger(DEBUG_ALWAYS, LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
205                 usleep(mesh->sleeptime * 1000000LL);
206                 mesh->sleeptime *= 2;
207                 if(mesh->sleeptime < 0)
208                         mesh->sleeptime = 3600;
209         } else {
210                 mesh->sleeptime /= 2;
211                 if(mesh->sleeptime < 10)
212                         mesh->sleeptime = 10;
213         }
214
215         mesh->contradicting_add_edge = 0;
216         mesh->contradicting_del_edge = 0;
217
218         int timeout = 5;
219
220         /* If AutoConnect is set, check if we need to make or break connections. */
221
222         if(autoconnect && mesh->nodes->count > 1) {
223                 /* Count number of active connections */
224                 int nc = 0;
225                 for list_each(connection_t, c, mesh->connections) {
226                         if(c->status.active)
227                                 nc++;
228                 }
229
230                 /* Count number of unreachable nodes */
231                 int num_unreachable = 0;
232                 for splay_each(node_t, n, mesh->nodes) {
233                         if(!n->status.reachable)
234                                 num_unreachable++;
235                 }
236
237                 if(nc < autoconnect) {
238                         /* Not enough active connections, try to add one.
239                            Choose a random node, if we don't have a connection to it,
240                            and we are not already trying to make one, create an
241                            outgoing connection to this node.
242                         */
243                         cond_add_connection(mesh, mesh->nodes->count, &found_random_node);
244                 } else if(num_unreachable > 0) {
245                         /* Min number of connections established. Now try
246                            to connect to some unreachable nodes to attempt
247                            to heal possible partitions.
248                         */
249                         cond_add_connection(mesh, num_unreachable, &found_random_unreachable_node);
250                 }
251                 
252                 if(nc > autoconnect) {
253                         /* Too many active connections, try to remove one.
254                            Choose a random outgoing connection to a node
255                            that has at least one other connection.
256                         */
257                         int r = rand() % nc;
258                         int i = 0;
259
260                         for list_each(connection_t, c, mesh->connections) {
261                                 if(!c->status.active)
262                                         continue;
263
264                                 if(i++ != r)
265                                         continue;
266
267                                 if(!c->outgoing || !c->node || c->node->edge_tree->count < 2)
268                                         break;
269
270                                 logger(DEBUG_CONNECTIONS, LOG_INFO, "Autodisconnecting from %s", c->name);
271                                 list_delete(mesh->outgoings, c->outgoing);
272                                 c->outgoing = NULL;
273                                 terminate_connection(mesh, c, c->status.active);
274                                 break;
275                         }
276                 }
277
278                 if(nc >= autoconnect) {
279                         /* If we have enough active connections,
280                            remove any pending outgoing connections.
281                            Do not remove pending connections to unreachable
282                            nodes.
283                         */
284                         node_t *o_node = NULL;
285                         for list_each(outgoing_t, o, mesh->outgoings) {
286                                 o_node = lookup_node(mesh, o->name);
287                                 /* o_node is NULL if it is not part of the graph yet */
288                                 if(!o_node || !o_node->status.reachable)
289                                         continue;
290
291                                 bool found = false;
292                                 for list_each(connection_t, c, mesh->connections) {
293                                         if(c->outgoing == o) {
294                                                 found = true;
295                                                 break;
296                                         }
297                                 }
298                                 if(!found) {
299                                         logger(DEBUG_CONNECTIONS, LOG_INFO, "Cancelled outgoing connection to %s", o->name);
300                                         /* The node variable is leaked in from using the list_each macro.
301                                            The o variable could be used, but using node directly
302                                            is more efficient.
303                                         */
304                                         list_delete_node(mesh->outgoings, node);
305                                 }
306                         }
307                 }
308
309                 if (nc + mesh->outgoings->count < min(autoconnect, mesh->nodes->count - 1))
310                         timeout = 0;
311         }
312
313         timeout_set(&mesh->loop, data, &(struct timeval){timeout, rand() % 100000});
314 }
315
316 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
317         if (!receive_meta(mesh, c)) {
318                 terminate_connection(mesh, c, c->status.active);
319                 return;
320         }
321 }
322
323 void retry(meshlink_handle_t *mesh) {
324         /* Reset the reconnection timers for all outgoing connections */
325         for list_each(outgoing_t, outgoing, mesh->outgoings) {
326                 outgoing->timeout = 0;
327                 if(outgoing->ev.cb)
328                         timeout_set(&mesh->loop, &outgoing->ev, &(struct timeval){0, 0});
329         }
330
331         /* Check for outgoing connections that are in progress, and reset their ping timers */
332         for list_each(connection_t, c, mesh->connections) {
333                 if(c->outgoing && !c->node)
334                         c->last_ping_time = 0;
335         }
336
337         /* Kick the ping timeout handler */
338         timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timeval){0, 0});
339 }
340
341 /*
342   this is where it all happens...
343 */
344 int main_loop(meshlink_handle_t *mesh) {
345         timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timeval){mesh->pingtimeout, rand() % 100000});
346         timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timeval){0, 0});
347
348         //Add signal handler
349         mesh->datafromapp.signum = 0;
350         signal_add(&(mesh->loop),&(mesh->datafromapp), (signal_cb_t)meshlink_send_from_queue,mesh, mesh->datafromapp.signum);
351
352         if(!event_loop_run(&mesh->loop)) {
353                 logger(DEBUG_ALWAYS, LOG_ERR, "Error while waiting for input: %s", strerror(errno));
354                 return 1;
355         }
356
357         timeout_del(&mesh->loop, &mesh->periodictimer);
358         timeout_del(&mesh->loop, &mesh->pingtimer);
359
360         return 0;
361 }