K&R style braces.
[oweals/tinc.git] / 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         cp();
56
57         ifdebug(PROTOCOL) logger(LOG_DEBUG, _("Purging unreachable nodes"));
58
59         /* Remove all edges and subnets owned by unreachable nodes. */
60
61         for(nnode = node_tree->head; nnode; nnode = nnext) {
62                 nnext = nnode->next;
63                 n = nnode->data;
64
65                 if(!n->status.reachable) {
66                         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Purging node %s (%s)"), n->name,
67                                            n->hostname);
68
69                         for(snode = n->subnet_tree->head; snode; snode = snext) {
70                                 snext = snode->next;
71                                 s = snode->data;
72                                 if(!tunnelserver)
73                                         send_del_subnet(broadcast, s);
74                                 subnet_del(n, s);
75                         }
76
77                         for(enode = n->edge_tree->head; enode; enode = enext) {
78                                 enext = enode->next;
79                                 e = enode->data;
80                                 if(!tunnelserver)
81                                         send_del_edge(broadcast, e);
82                                 edge_del(e);
83                         }
84                 }
85         }
86
87         /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
88
89         for(nnode = node_tree->head; nnode; nnode = nnext) {
90                 nnext = nnode->next;
91                 n = nnode->data;
92
93                 if(!n->status.reachable) {
94                         for(enode = edge_weight_tree->head; enode; enode = enext) {
95                                 enext = enode->next;
96                                 e = enode->data;
97
98                                 if(e->to == n)
99                                         break;
100                         }
101
102                         if(!enode)
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         cp();
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         cp();
165
166         if(c->status.remove)
167                 return;
168
169         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Closing connection with %s (%s)"),
170                            c->name, c->hostname);
171
172         c->status.remove = true;
173         c->status.active = false;
174
175         if(c->node)
176                 c->node->connection = NULL;
177
178         if(c->socket)
179                 closesocket(c->socket);
180
181         if(c->edge) {
182                 if(report && !tunnelserver)
183                         send_del_edge(broadcast, c->edge);
184
185                 edge_del(c->edge);
186
187                 /* Run MST and SSSP algorithms */
188
189                 graph();
190
191                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
192
193                 if(report && !c->node->status.reachable) {
194                         edge_t *e;
195                         e = lookup_edge(c->node, myself);
196                         if(e) {
197                                 if(!tunnelserver)
198                                         send_del_edge(broadcast, e);
199                                 edge_del(e);
200                         }
201                 }
202         }
203
204         /* Check if this was our outgoing connection */
205
206         if(c->outgoing) {
207                 retry_outgoing(c->outgoing);
208                 c->outgoing = NULL;
209         }
210
211         free(c->outbuf);
212         c->outbuf = NULL;
213         c->outbuflen = 0;
214         c->outbufsize = 0;
215         c->outbufstart = 0;
216 }
217
218 /*
219   Check if the other end is active.
220   If we have sent packets, but didn't receive any,
221   then possibly the other end is dead. We send a
222   PING request over the meta connection. If the other
223   end does not reply in time, we consider them dead
224   and close the connection.
225 */
226 static void check_dead_connections(void) {
227         avl_node_t *node, *next;
228         connection_t *c;
229
230         cp();
231
232         for(node = connection_tree->head; node; node = next) {
233                 next = node->next;
234                 c = node->data;
235
236                 if(c->last_ping_time + pingtimeout < now) {
237                         if(c->status.active) {
238                                 if(c->status.pinged) {
239                                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("%s (%s) didn't respond to PING in %ld seconds"),
240                                                            c->name, c->hostname, now - c->last_ping_time);
241                                         c->status.timeout = true;
242                                         terminate_connection(c, true);
243                                 } else if(c->last_ping_time + pinginterval < now) {
244                                         send_ping(c);
245                                 }
246                         } else {
247                                 if(c->status.remove) {
248                                         logger(LOG_WARNING, _("Old connection_t for %s (%s) status %04x still lingering, deleting..."),
249                                                    c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
250                                         connection_del(c);
251                                         continue;
252                                 }
253                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
254                                                    c->name, c->hostname);
255                                 if(c->status.connecting) {
256                                         c->status.connecting = false;
257                                         closesocket(c->socket);
258                                         do_outgoing_connection(c);
259                                 } else {
260                                         terminate_connection(c, false);
261                                 }
262                         }
263                 }
264
265                 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout < now) {
266                         if(c->status.active) {
267                                 ifdebug(CONNECTIONS) logger(LOG_INFO,
268                                                 _("%s (%s) could not flush for %ld seconds (%d bytes remaining)"),
269                                                 c->name, c->hostname, now - c->last_flushed_time, c->outbuflen);
270                                 c->status.timeout = true;
271                                 terminate_connection(c, true);
272                         }
273                 }
274         }
275 }
276
277 /*
278   check all connections to see if anything
279   happened on their sockets
280 */
281 static void check_network_activity(fd_set * readset, fd_set * writeset) {
282         connection_t *c;
283         avl_node_t *node;
284         int result, i;
285         socklen_t len = sizeof(result);
286         vpn_packet_t packet;
287
288         cp();
289
290         /* check input from kernel */
291         if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
292                 if(read_packet(&packet)) {
293                         packet.priority = 0;
294                         route(myself, &packet);
295                 }
296         }
297
298         /* check meta connections */
299         for(node = connection_tree->head; node; node = node->next) {
300                 c = node->data;
301
302                 if(c->status.remove)
303                         continue;
304
305                 if(FD_ISSET(c->socket, readset)) {
306                         if(c->status.connecting) {
307                                 c->status.connecting = false;
308                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, &result, &len);
309
310                                 if(!result)
311                                         finish_connecting(c);
312                                 else {
313                                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
314                                                            _("Error while connecting to %s (%s): %s"),
315                                                            c->name, c->hostname, strerror(result));
316                                         closesocket(c->socket);
317                                         do_outgoing_connection(c);
318                                         continue;
319                                 }
320                         }
321
322                         if(!receive_meta(c)) {
323                                 terminate_connection(c, c->status.active);
324                                 continue;
325                         }
326                 }
327
328                 if(FD_ISSET(c->socket, writeset)) {
329                         if(!flush_meta(c)) {
330                                 terminate_connection(c, c->status.active);
331                                 continue;
332                         }
333                 }
334         }
335
336         for(i = 0; i < listen_sockets; i++) {
337                 if(FD_ISSET(listen_socket[i].udp, readset))
338                         handle_incoming_vpn_data(listen_socket[i].udp);
339
340                 if(FD_ISSET(listen_socket[i].tcp, readset))
341                         handle_new_meta_connection(listen_socket[i].tcp);
342         }
343 }
344
345 /*
346   this is where it all happens...
347 */
348 int main_loop(void) {
349         fd_set readset, writeset;
350         struct timeval tv;
351         int r, maxfd;
352         time_t last_ping_check, last_config_check, last_graph_dump;
353         event_t *event;
354
355         cp();
356
357         last_ping_check = now;
358         last_config_check = now;
359         last_graph_dump = now;
360         
361         srand(now);
362
363         running = true;
364
365         while(running) {
366                 now = time(NULL);
367
368         //      tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
369                 tv.tv_sec = 1;
370                 tv.tv_usec = 0;
371
372                 maxfd = build_fdset(&readset, &writeset);
373
374 #ifdef HAVE_MINGW
375                 LeaveCriticalSection(&mutex);
376 #endif
377                 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
378 #ifdef HAVE_MINGW
379                 EnterCriticalSection(&mutex);
380 #endif
381
382                 if(r < 0) {
383                         if(errno != EINTR && errno != EAGAIN) {
384                                 logger(LOG_ERR, _("Error while waiting for input: %s"),
385                                            strerror(errno));
386                                 cp_trace();
387                                 dump_connections();
388                                 return 1;
389                         }
390
391                         continue;
392                 }
393
394                 check_network_activity(&readset, &writeset);
395
396                 if(do_purge) {
397                         purge();
398                         do_purge = false;
399                 }
400
401                 /* Let's check if everybody is still alive */
402
403                 if(last_ping_check + pingtimeout < now) {
404                         check_dead_connections();
405                         last_ping_check = now;
406
407                         if(routing_mode == RMODE_SWITCH)
408                                 age_subnets();
409
410                         age_past_requests();
411
412                         /* Should we regenerate our key? */
413
414                         if(keyexpires < now) {
415                                 avl_node_t *node;
416                                 node_t *n;
417
418                                 ifdebug(STATUS) logger(LOG_INFO, _("Expiring symmetric keys"));
419
420                                 for(node = node_tree->head; node; node = node->next) {
421                                         n = node->data;
422                                         if(n->inkey) {
423                                                 free(n->inkey);
424                                                 n->inkey = NULL;
425                                         }
426                                 }
427
428                                 send_key_changed(broadcast, myself);
429                                 keyexpires = now + keylifetime;
430                         }
431                 }
432
433                 if(sigalrm) {
434                         logger(LOG_INFO, _("Flushing event queue"));
435                         expire_events();
436                         sigalrm = false;
437                 }
438
439                 while((event = get_expired_event())) {
440                         event->handler(event->data);
441                         free_event(event);
442                 }
443
444                 if(sighup) {
445                         connection_t *c;
446                         avl_node_t *node;
447                         char *fname;
448                         struct stat s;
449                         
450                         sighup = false;
451                         
452                         /* Reread our own configuration file */
453
454                         exit_configuration(&config_tree);
455                         init_configuration(&config_tree);
456
457                         if(!read_server_config()) {
458                                 logger(LOG_ERR, _("Unable to reread configuration file, exitting."));
459                                 return 1;
460                         }
461
462                         /* Close connections to hosts that have a changed or deleted host config file */
463                         
464                         for(node = connection_tree->head; node; node = node->next) {
465                                 c = node->data;
466                                 
467                                 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
468                                 if(stat(fname, &s) || s.st_mtime > last_config_check)
469                                         terminate_connection(c, c->status.active);
470                                 free(fname);
471                         }
472
473                         last_config_check = now;
474
475                         /* Try to make outgoing connections */
476                         
477                         try_outgoing_connections();
478                 }
479                 
480                 /* Dump graph if wanted every 60 seconds*/
481
482                 if(last_graph_dump + 60 < now) {
483                         dump_graph();
484                         last_graph_dump = now;
485                 }
486         }
487
488         return 0;
489 }