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