6ffd9989d5d4356e6e83c1e3cc08edfa20e16b08
[tinc] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2010 Guus Sliepen <guus@tinc-vpn.org>
5                   2006      Scott Lamb <slamb@slamb.org>
6
7     This program is free software; you can redistribute it and/or modify
8     it under the terms of the GNU General Public License as published by
9     the Free Software Foundation; either version 2 of the License, or
10     (at your option) any later version.
11
12     This program is distributed in the hope that it will be useful,
13     but WITHOUT ANY WARRANTY; without even the implied warranty of
14     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15     GNU General Public License for more details.
16
17     You should have received a copy of the GNU General Public License along
18     with this program; if not, write to the Free Software Foundation, Inc.,
19     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 */
21
22 #include "system.h"
23
24 #include <openssl/rand.h>
25
26 #include "utils.h"
27 #include "avl_tree.h"
28 #include "conf.h"
29 #include "connection.h"
30 #include "device.h"
31 #include "event.h"
32 #include "graph.h"
33 #include "logger.h"
34 #include "meta.h"
35 #include "net.h"
36 #include "netutl.h"
37 #include "process.h"
38 #include "protocol.h"
39 #include "route.h"
40 #include "subnet.h"
41 #include "xalloc.h"
42
43 bool do_purge = false;
44 volatile bool running = false;
45
46 time_t now = 0;
47
48 /* Purge edges and subnets of unreachable nodes. Use carefully. */
49
50 static void purge(void) {
51         avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
52         node_t *n;
53         edge_t *e;
54         subnet_t *s;
55
56         ifdebug(PROTOCOL) logger(LOG_DEBUG, "Purging unreachable nodes");
57
58         /* Remove all edges and subnets owned by unreachable nodes. */
59
60         for(nnode = node_tree->head; nnode; nnode = nnext) {
61                 nnext = nnode->next;
62                 n = nnode->data;
63
64                 if(!n->status.reachable) {
65                         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Purging node %s (%s)", n->name,
66                                            n->hostname);
67
68                         for(snode = n->subnet_tree->head; snode; snode = snext) {
69                                 snext = snode->next;
70                                 s = snode->data;
71                                 send_del_subnet(broadcast, s);
72                                 if(!strictsubnets)
73                                         subnet_del(n, s);
74                         }
75
76                         for(enode = n->edge_tree->head; enode; enode = enext) {
77                                 enext = enode->next;
78                                 e = enode->data;
79                                 if(!tunnelserver)
80                                         send_del_edge(broadcast, e);
81                                 edge_del(e);
82                         }
83                 }
84         }
85
86         /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
87
88         for(nnode = node_tree->head; nnode; nnode = nnext) {
89                 nnext = nnode->next;
90                 n = nnode->data;
91
92                 if(!n->status.reachable) {
93                         for(enode = edge_weight_tree->head; enode; enode = enext) {
94                                 enext = enode->next;
95                                 e = enode->data;
96
97                                 if(e->to == n)
98                                         break;
99                         }
100
101                         if(!enode && (!strictsubnets || !n->subnet_tree->head))
102                                 /* in strictsubnets mode do not delete nodes with subnets */
103                                 node_del(n);
104                 }
105         }
106 }
107
108 /*
109   put all file descriptors in an fd_set array
110   While we're at it, purge stuff that needs to be removed.
111 */
112 static int build_fdset(fd_set *readset, fd_set *writeset) {
113         avl_node_t *node, *next;
114         connection_t *c;
115         int i, max = 0;
116
117         FD_ZERO(readset);
118         FD_ZERO(writeset);
119
120         for(node = connection_tree->head; node; node = next) {
121                 next = node->next;
122                 c = node->data;
123
124                 if(c->status.remove) {
125                         connection_del(c);
126                         if(!connection_tree->head)
127                                 purge();
128                 } else {
129                         FD_SET(c->socket, readset);
130                         if(c->outbuflen > 0)
131                                 FD_SET(c->socket, writeset);
132                         if(c->socket > max)
133                                 max = c->socket;
134                 }
135         }
136
137         for(i = 0; i < listen_sockets; i++) {
138                 FD_SET(listen_socket[i].tcp, readset);
139                 if(listen_socket[i].tcp > max)
140                         max = listen_socket[i].tcp;
141                 FD_SET(listen_socket[i].udp, readset);
142                 if(listen_socket[i].udp > max)
143                         max = listen_socket[i].udp;
144         }
145
146         if(device_fd >= 0)
147                 FD_SET(device_fd, readset);
148         if(device_fd > max)
149                 max = device_fd;
150         
151         return max;
152 }
153
154 /*
155   Terminate a connection:
156   - Close the socket
157   - Remove associated edge and tell other connections about it if report = true
158   - Check if we need to retry making an outgoing connection
159   - Deactivate the host
160 */
161 void terminate_connection(connection_t *c, bool report) {
162         if(c->status.remove)
163                 return;
164
165         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Closing connection with %s (%s)",
166                            c->name, c->hostname);
167
168         c->status.remove = true;
169         c->status.active = false;
170
171         if(c->node)
172                 c->node->connection = NULL;
173
174         if(c->socket)
175                 closesocket(c->socket);
176
177         if(c->edge) {
178                 if(report && !tunnelserver)
179                         send_del_edge(broadcast, c->edge);
180
181                 edge_del(c->edge);
182
183                 /* Run MST and SSSP algorithms */
184
185                 graph();
186
187                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
188
189                 if(report && !c->node->status.reachable) {
190                         edge_t *e;
191                         e = lookup_edge(c->node, myself);
192                         if(e) {
193                                 if(!tunnelserver)
194                                         send_del_edge(broadcast, e);
195                                 edge_del(e);
196                         }
197                 }
198         }
199
200         /* Check if this was our outgoing connection */
201
202         if(c->outgoing) {
203                 retry_outgoing(c->outgoing);
204                 c->outgoing = NULL;
205         }
206
207         free(c->outbuf);
208         c->outbuf = NULL;
209         c->outbuflen = 0;
210         c->outbufsize = 0;
211         c->outbufstart = 0;
212 }
213
214 /*
215   Check if the other end is active.
216   If we have sent packets, but didn't receive any,
217   then possibly the other end is dead. We send a
218   PING request over the meta connection. If the other
219   end does not reply in time, we consider them dead
220   and close the connection.
221 */
222 static void check_dead_connections(void) {
223         avl_node_t *node, *next;
224         connection_t *c;
225
226         for(node = connection_tree->head; node; node = next) {
227                 next = node->next;
228                 c = node->data;
229
230                 if(c->last_ping_time + pingtimeout < now) {
231                         if(c->status.active) {
232                                 if(c->status.pinged) {
233                                         ifdebug(CONNECTIONS) logger(LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds",
234                                                            c->name, c->hostname, now - c->last_ping_time);
235                                         c->status.timeout = true;
236                                         terminate_connection(c, true);
237                                 } else if(c->last_ping_time + pinginterval < now) {
238                                         send_ping(c);
239                                 }
240                         } else {
241                                 if(c->status.remove) {
242                                         logger(LOG_WARNING, "Old connection_t for %s (%s) status %04x still lingering, deleting...",
243                                                    c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
244                                         connection_del(c);
245                                         continue;
246                                 }
247                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, "Timeout from %s (%s) during authentication",
248                                                    c->name, c->hostname);
249                                 if(c->status.connecting) {
250                                         c->status.connecting = false;
251                                         closesocket(c->socket);
252                                         do_outgoing_connection(c);
253                                 } else {
254                                         terminate_connection(c, false);
255                                 }
256                         }
257                 }
258
259                 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout < now) {
260                         if(c->status.active) {
261                                 ifdebug(CONNECTIONS) logger(LOG_INFO,
262                                                 "%s (%s) could not flush for %ld seconds (%d bytes remaining)",
263                                                 c->name, c->hostname, now - c->last_flushed_time, c->outbuflen);
264                                 c->status.timeout = true;
265                                 terminate_connection(c, true);
266                         }
267                 }
268         }
269 }
270
271 /*
272   check all connections to see if anything
273   happened on their sockets
274 */
275 static void check_network_activity(fd_set * readset, fd_set * writeset) {
276         connection_t *c;
277         avl_node_t *node;
278         int result, i;
279         socklen_t len = sizeof(result);
280         vpn_packet_t packet;
281
282         /* check input from kernel */
283         if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
284                 if(read_packet(&packet)) {
285                         packet.priority = 0;
286                         route(myself, &packet);
287                 }
288         }
289
290         /* check meta connections */
291         for(node = connection_tree->head; node; node = node->next) {
292                 c = node->data;
293
294                 if(c->status.remove)
295                         continue;
296
297                 if(FD_ISSET(c->socket, readset)) {
298                         if(c->status.connecting) {
299                                 c->status.connecting = false;
300                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, &result, &len);
301
302                                 if(!result)
303                                         finish_connecting(c);
304                                 else {
305                                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
306                                                            "Error while connecting to %s (%s): %s",
307                                                            c->name, c->hostname, sockstrerror(result));
308                                         closesocket(c->socket);
309                                         do_outgoing_connection(c);
310                                         continue;
311                                 }
312                         }
313
314                         if(!receive_meta(c)) {
315                                 terminate_connection(c, c->status.active);
316                                 continue;
317                         }
318                 }
319
320                 if(FD_ISSET(c->socket, writeset)) {
321                         if(!flush_meta(c)) {
322                                 terminate_connection(c, c->status.active);
323                                 continue;
324                         }
325                 }
326         }
327
328         for(i = 0; i < listen_sockets; i++) {
329                 if(FD_ISSET(listen_socket[i].udp, readset))
330                         handle_incoming_vpn_data(listen_socket[i].udp);
331
332                 if(FD_ISSET(listen_socket[i].tcp, readset))
333                         handle_new_meta_connection(listen_socket[i].tcp);
334         }
335 }
336
337 /*
338   this is where it all happens...
339 */
340 int main_loop(void) {
341         fd_set readset, writeset;
342         struct timeval tv;
343         int r, maxfd;
344         time_t last_ping_check, last_config_check, last_graph_dump;
345         event_t *event;
346
347         last_ping_check = now;
348         last_config_check = now;
349         last_graph_dump = now;
350         
351         srand(now);
352
353         running = true;
354
355         while(running) {
356                 now = time(NULL);
357
358         //      tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
359                 tv.tv_sec = 1;
360                 tv.tv_usec = 0;
361
362                 maxfd = build_fdset(&readset, &writeset);
363
364 #ifdef HAVE_MINGW
365                 LeaveCriticalSection(&mutex);
366 #endif
367                 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
368 #ifdef HAVE_MINGW
369                 EnterCriticalSection(&mutex);
370 #endif
371
372                 if(r < 0) {
373                         if(!sockwouldblock(sockerrno)) {
374                                 logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
375                                 dump_connections();
376                                 return 1;
377                         }
378                 }
379
380                 if(r > 0)
381                         check_network_activity(&readset, &writeset);
382
383                 if(do_purge) {
384                         purge();
385                         do_purge = false;
386                 }
387
388                 /* Let's check if everybody is still alive */
389
390                 if(last_ping_check + pingtimeout < now) {
391                         check_dead_connections();
392                         last_ping_check = now;
393
394                         if(routing_mode == RMODE_SWITCH)
395                                 age_subnets();
396
397                         age_past_requests();
398
399                         /* Should we regenerate our key? */
400
401                         if(keyexpires < now) {
402                                 avl_node_t *node;
403                                 node_t *n;
404
405                                 ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
406
407                                 for(node = node_tree->head; node; node = node->next) {
408                                         n = node->data;
409                                         if(n->inkey) {
410                                                 free(n->inkey);
411                                                 n->inkey = NULL;
412                                         }
413                                 }
414
415                                 send_key_changed(broadcast, myself);
416                                 keyexpires = now + keylifetime;
417                         }
418                 }
419
420                 if(sigalrm) {
421                         avl_node_t *node;
422                         logger(LOG_INFO, "Flushing event queue");
423                         expire_events();
424                         for(node = connection_tree->head; node; node = node->next) {
425                                 connection_t *c = node->data;
426                                 send_ping(c);
427                         }
428                         sigalrm = false;
429                 }
430
431                 while((event = get_expired_event())) {
432                         event->handler(event->data);
433                         free_event(event);
434                 }
435
436                 if(sighup) {
437                         connection_t *c;
438                         avl_node_t *node, *next;
439                         char *fname;
440                         struct stat s;
441                         
442                         sighup = false;
443                         
444                         /* Reread our own configuration file */
445
446                         exit_configuration(&config_tree);
447                         init_configuration(&config_tree);
448
449                         if(!read_server_config()) {
450                                 logger(LOG_ERR, "Unable to reread configuration file, exitting.");
451                                 return 1;
452                         }
453
454                         /* Cancel non-active outgoing connections */
455
456                         for(node = connection_tree->head; node; node = next) {
457                                 next = node->next;
458                                 c = node->data;
459
460                                 c->outgoing = NULL;
461
462                                 if(c->status.connecting) {
463                                         terminate_connection(c, false);
464                                         connection_del(c);
465                                 }
466                         }
467
468                         /* Wipe list of outgoing connections */
469
470                         for(list_node_t *node = outgoing_list->head; node; node = node->next) {
471                                 outgoing_t *outgoing = node->data;
472
473                                 if(outgoing->event)
474                                         event_del(outgoing->event);
475                         }
476
477                         list_delete_list(outgoing_list);
478
479                         /* Close connections to hosts that have a changed or deleted host config file */
480                         
481                         for(node = connection_tree->head; node; node = node->next) {
482                                 c = node->data;
483                                 
484                                 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
485                                 if(stat(fname, &s) || s.st_mtime > last_config_check)
486                                         terminate_connection(c, c->status.active);
487                                 free(fname);
488                         }
489
490                         last_config_check = now;
491
492                         /* Try to make outgoing connections */
493                         
494                         try_outgoing_connections();
495                 }
496                 
497                 /* Dump graph if wanted every 60 seconds*/
498
499                 if(last_graph_dump + 60 < now) {
500                         dump_graph();
501                         last_graph_dump = now;
502                 }
503         }
504
505         return 0;
506 }