Detect and prevent two nodes with the same Name being on the VPN simultaneously.
[oweals/tinc.git] / 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 int contradicting_add_edge = 0;
48 int contradicting_del_edge = 0;
49
50 /* Purge edges and subnets of unreachable nodes. Use carefully. */
51
52 static void purge(void) {
53         avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
54         node_t *n;
55         edge_t *e;
56         subnet_t *s;
57
58         ifdebug(PROTOCOL) logger(LOG_DEBUG, "Purging unreachable nodes");
59
60         /* Remove all edges and subnets owned by unreachable nodes. */
61
62         for(nnode = node_tree->head; nnode; nnode = nnext) {
63                 nnext = nnode->next;
64                 n = nnode->data;
65
66                 if(!n->status.reachable) {
67                         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Purging node %s (%s)", n->name,
68                                            n->hostname);
69
70                         for(snode = n->subnet_tree->head; snode; snode = snext) {
71                                 snext = snode->next;
72                                 s = snode->data;
73                                 send_del_subnet(broadcast, s);
74                                 if(!strictsubnets)
75                                         subnet_del(n, s);
76                         }
77
78                         for(enode = n->edge_tree->head; enode; enode = enext) {
79                                 enext = enode->next;
80                                 e = enode->data;
81                                 if(!tunnelserver)
82                                         send_del_edge(broadcast, e);
83                                 edge_del(e);
84                         }
85                 }
86         }
87
88         /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
89
90         for(nnode = node_tree->head; nnode; nnode = nnext) {
91                 nnext = nnode->next;
92                 n = nnode->data;
93
94                 if(!n->status.reachable) {
95                         for(enode = edge_weight_tree->head; enode; enode = enext) {
96                                 enext = enode->next;
97                                 e = enode->data;
98
99                                 if(e->to == n)
100                                         break;
101                         }
102
103                         if(!enode && (!strictsubnets || !n->subnet_tree->head))
104                                 /* in strictsubnets mode do not delete nodes with subnets */
105                                 node_del(n);
106                 }
107         }
108 }
109
110 /*
111   put all file descriptors in an fd_set array
112   While we're at it, purge stuff that needs to be removed.
113 */
114 static int build_fdset(fd_set *readset, fd_set *writeset) {
115         avl_node_t *node, *next;
116         connection_t *c;
117         int i, max = 0;
118
119         FD_ZERO(readset);
120         FD_ZERO(writeset);
121
122         for(node = connection_tree->head; node; node = next) {
123                 next = node->next;
124                 c = node->data;
125
126                 if(c->status.remove) {
127                         connection_del(c);
128                         if(!connection_tree->head)
129                                 purge();
130                 } else {
131                         FD_SET(c->socket, readset);
132                         if(c->outbuflen > 0)
133                                 FD_SET(c->socket, writeset);
134                         if(c->socket > max)
135                                 max = c->socket;
136                 }
137         }
138
139         for(i = 0; i < listen_sockets; i++) {
140                 FD_SET(listen_socket[i].tcp, readset);
141                 if(listen_socket[i].tcp > max)
142                         max = listen_socket[i].tcp;
143                 FD_SET(listen_socket[i].udp, readset);
144                 if(listen_socket[i].udp > max)
145                         max = listen_socket[i].udp;
146         }
147
148         if(device_fd >= 0)
149                 FD_SET(device_fd, readset);
150         if(device_fd > max)
151                 max = device_fd;
152         
153         return max;
154 }
155
156 /*
157   Terminate a connection:
158   - Close the socket
159   - Remove associated edge and tell other connections about it if report = true
160   - Check if we need to retry making an outgoing connection
161   - Deactivate the host
162 */
163 void terminate_connection(connection_t *c, bool report) {
164         if(c->status.remove)
165                 return;
166
167         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Closing connection with %s (%s)",
168                            c->name, c->hostname);
169
170         c->status.remove = true;
171         c->status.active = false;
172
173         if(c->node)
174                 c->node->connection = NULL;
175
176         if(c->socket)
177                 closesocket(c->socket);
178
179         if(c->edge) {
180                 if(report && !tunnelserver)
181                         send_del_edge(broadcast, c->edge);
182
183                 edge_del(c->edge);
184
185                 /* Run MST and SSSP algorithms */
186
187                 graph();
188
189                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
190
191                 if(report && !c->node->status.reachable) {
192                         edge_t *e;
193                         e = lookup_edge(c->node, myself);
194                         if(e) {
195                                 if(!tunnelserver)
196                                         send_del_edge(broadcast, e);
197                                 edge_del(e);
198                         }
199                 }
200         }
201
202         /* Check if this was our outgoing connection */
203
204         if(c->outgoing) {
205                 retry_outgoing(c->outgoing);
206                 c->outgoing = NULL;
207         }
208
209         free(c->outbuf);
210         c->outbuf = NULL;
211         c->outbuflen = 0;
212         c->outbufsize = 0;
213         c->outbufstart = 0;
214 }
215
216 /*
217   Check if the other end is active.
218   If we have sent packets, but didn't receive any,
219   then possibly the other end is dead. We send a
220   PING request over the meta connection. If the other
221   end does not reply in time, we consider them dead
222   and close the connection.
223 */
224 static void check_dead_connections(void) {
225         avl_node_t *node, *next;
226         connection_t *c;
227
228         for(node = connection_tree->head; node; node = next) {
229                 next = node->next;
230                 c = node->data;
231
232                 if(c->last_ping_time + pingtimeout < now) {
233                         if(c->status.active) {
234                                 if(c->status.pinged) {
235                                         ifdebug(CONNECTIONS) logger(LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds",
236                                                            c->name, c->hostname, now - c->last_ping_time);
237                                         c->status.timeout = true;
238                                         terminate_connection(c, true);
239                                 } else if(c->last_ping_time + pinginterval < now) {
240                                         send_ping(c);
241                                 }
242                         } else {
243                                 if(c->status.remove) {
244                                         logger(LOG_WARNING, "Old connection_t for %s (%s) status %04x still lingering, deleting...",
245                                                    c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
246                                         connection_del(c);
247                                         continue;
248                                 }
249                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, "Timeout from %s (%s) during authentication",
250                                                    c->name, c->hostname);
251                                 if(c->status.connecting) {
252                                         c->status.connecting = false;
253                                         closesocket(c->socket);
254                                         do_outgoing_connection(c);
255                                 } else {
256                                         terminate_connection(c, false);
257                                 }
258                         }
259                 }
260
261                 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout < now) {
262                         if(c->status.active) {
263                                 ifdebug(CONNECTIONS) logger(LOG_INFO,
264                                                 "%s (%s) could not flush for %ld seconds (%d bytes remaining)",
265                                                 c->name, c->hostname, now - c->last_flushed_time, c->outbuflen);
266                                 c->status.timeout = true;
267                                 terminate_connection(c, true);
268                         }
269                 }
270         }
271 }
272
273 /*
274   check all connections to see if anything
275   happened on their sockets
276 */
277 static void check_network_activity(fd_set * readset, fd_set * writeset) {
278         connection_t *c;
279         avl_node_t *node;
280         int result, i;
281         socklen_t len = sizeof(result);
282         vpn_packet_t packet;
283
284         /* check input from kernel */
285         if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
286                 if(read_packet(&packet)) {
287                         packet.priority = 0;
288                         route(myself, &packet);
289                 }
290         }
291
292         /* check meta connections */
293         for(node = connection_tree->head; node; node = node->next) {
294                 c = node->data;
295
296                 if(c->status.remove)
297                         continue;
298
299                 if(FD_ISSET(c->socket, readset)) {
300                         if(c->status.connecting) {
301                                 c->status.connecting = false;
302                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
303
304                                 if(!result)
305                                         finish_connecting(c);
306                                 else {
307                                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
308                                                            "Error while connecting to %s (%s): %s",
309                                                            c->name, c->hostname, sockstrerror(result));
310                                         closesocket(c->socket);
311                                         do_outgoing_connection(c);
312                                         continue;
313                                 }
314                         }
315
316                         if(!receive_meta(c)) {
317                                 terminate_connection(c, c->status.active);
318                                 continue;
319                         }
320                 }
321
322                 if(FD_ISSET(c->socket, writeset)) {
323                         if(!flush_meta(c)) {
324                                 terminate_connection(c, c->status.active);
325                                 continue;
326                         }
327                 }
328         }
329
330         for(i = 0; i < listen_sockets; i++) {
331                 if(FD_ISSET(listen_socket[i].udp, readset))
332                         handle_incoming_vpn_data(listen_socket[i].udp);
333
334                 if(FD_ISSET(listen_socket[i].tcp, readset))
335                         handle_new_meta_connection(listen_socket[i].tcp);
336         }
337 }
338
339 /*
340   this is where it all happens...
341 */
342 int main_loop(void) {
343         fd_set readset, writeset;
344         struct timeval tv;
345         int r, maxfd;
346         time_t last_ping_check, last_config_check, last_graph_dump;
347         event_t *event;
348
349         last_ping_check = now;
350         last_config_check = now;
351         last_graph_dump = now;
352         
353         srand(now);
354
355         running = true;
356
357         while(running) {
358                 now = time(NULL);
359
360         //      tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
361                 tv.tv_sec = 1;
362                 tv.tv_usec = 0;
363
364                 maxfd = build_fdset(&readset, &writeset);
365
366 #ifdef HAVE_MINGW
367                 LeaveCriticalSection(&mutex);
368 #endif
369                 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
370 #ifdef HAVE_MINGW
371                 EnterCriticalSection(&mutex);
372 #endif
373
374                 if(r < 0) {
375                         if(!sockwouldblock(sockerrno)) {
376                                 logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
377                                 dump_connections();
378                                 return 1;
379                         }
380                 }
381
382                 if(r > 0)
383                         check_network_activity(&readset, &writeset);
384
385                 if(do_purge) {
386                         purge();
387                         do_purge = false;
388                 }
389
390                 /* Let's check if everybody is still alive */
391
392                 if(last_ping_check + pingtimeout < now) {
393                         check_dead_connections();
394                         last_ping_check = now;
395
396                         if(routing_mode == RMODE_SWITCH)
397                                 age_subnets();
398
399                         age_past_requests();
400
401                         /* Should we regenerate our key? */
402
403                         if(keyexpires < now) {
404                                 avl_node_t *node;
405                                 node_t *n;
406
407                                 ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
408
409                                 for(node = node_tree->head; node; node = node->next) {
410                                         n = node->data;
411                                         if(n->inkey) {
412                                                 free(n->inkey);
413                                                 n->inkey = NULL;
414                                         }
415                                 }
416
417                                 send_key_changed(broadcast, myself);
418                                 keyexpires = now + keylifetime;
419                         }
420
421                         if(contradicting_del_edge && contradicting_add_edge) {
422                                 logger(LOG_WARNING, "Possible node with same Name as us!");
423
424                                 if(rand() % 3 == 0) {
425                                         logger(LOG_ERR, "Shutting down, check configuration of all nodes for duplicate Names!");
426                                         running = false;
427                                         break;
428                                 }
429
430                                 contradicting_add_edge = 0;
431                                 contradicting_del_edge = 0;
432                         }
433                 }
434
435                 if(sigalrm) {
436                         avl_node_t *node;
437                         logger(LOG_INFO, "Flushing event queue");
438                         expire_events();
439                         for(node = connection_tree->head; node; node = node->next) {
440                                 connection_t *c = node->data;
441                                 send_ping(c);
442                         }
443                         sigalrm = false;
444                 }
445
446                 while((event = get_expired_event())) {
447                         event->handler(event->data);
448                         free_event(event);
449                 }
450
451                 if(sighup) {
452                         connection_t *c;
453                         avl_node_t *node, *next;
454                         char *fname;
455                         struct stat s;
456                         
457                         sighup = false;
458                         
459                         /* Reread our own configuration file */
460
461                         exit_configuration(&config_tree);
462                         init_configuration(&config_tree);
463
464                         if(!read_server_config()) {
465                                 logger(LOG_ERR, "Unable to reread configuration file, exitting.");
466                                 return 1;
467                         }
468
469                         /* Cancel non-active outgoing connections */
470
471                         for(node = connection_tree->head; node; node = next) {
472                                 next = node->next;
473                                 c = node->data;
474
475                                 c->outgoing = NULL;
476
477                                 if(c->status.connecting) {
478                                         terminate_connection(c, false);
479                                         connection_del(c);
480                                 }
481                         }
482
483                         /* Wipe list of outgoing connections */
484
485                         for(list_node_t *node = outgoing_list->head; node; node = node->next) {
486                                 outgoing_t *outgoing = node->data;
487
488                                 if(outgoing->event)
489                                         event_del(outgoing->event);
490                         }
491
492                         list_delete_list(outgoing_list);
493
494                         /* Close connections to hosts that have a changed or deleted host config file */
495                         
496                         for(node = connection_tree->head; node; node = node->next) {
497                                 c = node->data;
498                                 
499                                 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
500                                 if(stat(fname, &s) || s.st_mtime > last_config_check)
501                                         terminate_connection(c, c->status.active);
502                                 free(fname);
503                         }
504
505                         last_config_check = now;
506
507                         /* If StrictSubnet is set, expire deleted Subnets and read new ones in */
508
509                         if(strictsubnets) {
510                                 subnet_t *subnet;
511
512                                 for(node = subnet_tree->head; node; node = node->next) {
513                                         subnet = node->data;
514                                         subnet->expires = 1;
515                                 }
516
517                                 load_all_subnets();
518
519                                 for(node = subnet_tree->head; node; node = next) {
520                                         next = node->next;
521                                         subnet = node->data;
522                                         if(subnet->expires == 1) {
523                                                 send_del_subnet(broadcast, subnet);
524                                                 if(subnet->owner->status.reachable)
525                                                         subnet_update(subnet->owner, subnet, false);
526                                                 subnet_del(subnet->owner, subnet);
527                                         } else if(subnet->expires == -1) {
528                                                 subnet->expires = 0;
529                                         } else {
530                                                 send_add_subnet(broadcast, subnet);
531                                                 if(subnet->owner->status.reachable)
532                                                         subnet_update(subnet->owner, subnet, true);
533                                         }
534                                 }
535                         }
536
537                         /* Try to make outgoing connections */
538                         
539                         try_outgoing_connections();
540                 }
541                 
542                 /* Dump graph if wanted every 60 seconds*/
543
544                 if(last_graph_dump + 60 < now) {
545                         dump_graph();
546                         last_graph_dump = now;
547                 }
548         }
549
550         return 0;
551 }