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