Simplify logging, update copyrights and some minor cleanups.
[tinc] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998-2003 Ivo Timmermans <ivo@o2w.nl>,
4                   2000-2003 Guus Sliepen <guus@sliepen.eu.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
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: net.c,v 1.35.4.190 2003/07/12 17:41:45 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <netdb.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <signal.h>
32 #include <sys/time.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <unistd.h>
36 #include <sys/ioctl.h>
37 /* SunOS really wants sys/socket.h BEFORE net/if.h,
38    and FreeBSD wants these lines below the rest. */
39 #include <arpa/inet.h>
40 #include <sys/socket.h>
41 #include <net/if.h>
42 #ifdef HAVE_NETINET_IN_SYSTM_H
43 #include <netinet/in_systm.h>
44 #endif
45 #include <netinet/in.h>
46 #ifdef HAVE_NETINET_IP_H
47 #include <netinet/ip.h>
48 #endif
49 #ifdef HAVE_NETINET_TCP_H
50 #include <netinet/tcp.h>
51 #endif
52
53 #include <openssl/rand.h>
54
55 #include <utils.h>
56 #include <xalloc.h>
57 #include <avl_tree.h>
58 #include <list.h>
59
60 #include "conf.h"
61 #include "connection.h"
62 #include "meta.h"
63 #include "net.h"
64 #include "netutl.h"
65 #include "process.h"
66 #include "protocol.h"
67 #include "subnet.h"
68 #include "graph.h"
69 #include "process.h"
70 #include "route.h"
71 #include "device.h"
72 #include "event.h"
73 #include "logger.h"
74
75 #include "system.h"
76
77 int do_purge = 0;
78 int sighup = 0;
79 int sigalrm = 0;
80
81 time_t now = 0;
82
83 /* Purge edges and subnets of unreachable nodes. Use carefully. */
84
85 static void purge(void)
86 {
87         avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
88         node_t *n;
89         edge_t *e;
90         subnet_t *s;
91
92         cp();
93
94         ifdebug(PROTOCOL) logger(LOG_DEBUG, _("Purging unreachable nodes"));
95
96         for(nnode = node_tree->head; nnode; nnode = nnext) {
97                 nnext = nnode->next;
98                 n = (node_t *) nnode->data;
99
100                 if(!n->status.reachable) {
101                         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Purging node %s (%s)"), n->name,
102                                            n->hostname);
103
104                         for(snode = n->subnet_tree->head; snode; snode = snext) {
105                                 snext = snode->next;
106                                 s = (subnet_t *) snode->data;
107                                 send_del_subnet(broadcast, s);
108                                 subnet_del(n, s);
109                         }
110
111                         for(enode = n->edge_tree->head; enode; enode = enext) {
112                                 enext = enode->next;
113                                 e = (edge_t *) enode->data;
114                                 send_del_edge(broadcast, e);
115                                 edge_del(e);
116                         }
117
118                         node_del(n);
119                 }
120         }
121 }
122
123 /*
124   put all file descriptors in an fd_set array
125   While we're at it, purge stuff that needs to be removed.
126 */
127 static int build_fdset(fd_set * fs)
128 {
129         avl_node_t *node, *next;
130         connection_t *c;
131         int i, max = 0;
132
133         cp();
134
135         FD_ZERO(fs);
136
137         for(node = connection_tree->head; node; node = next) {
138                 next = node->next;
139                 c = (connection_t *) node->data;
140
141                 if(c->status.remove) {
142                         connection_del(c);
143                         if(!connection_tree->head)
144                                 purge();
145                 } else {
146                         FD_SET(c->socket, fs);
147                         if(c->socket > max)
148                                 max = c->socket;
149                 }
150         }
151
152         for(i = 0; i < listen_sockets; i++) {
153                 FD_SET(listen_socket[i].tcp, fs);
154                 if(listen_socket[i].tcp > max)
155                         max = listen_socket[i].tcp;
156                 FD_SET(listen_socket[i].udp, fs);
157                 if(listen_socket[i].udp > max)
158                         max = listen_socket[i].udp;
159         }
160
161         FD_SET(device_fd, fs);
162         if(device_fd > max)
163                 max = device_fd;
164         
165         return max;
166 }
167
168 /*
169   Terminate a connection:
170   - Close the socket
171   - Remove associated edge and tell other connections about it if report = 1
172   - Check if we need to retry making an outgoing connection
173   - Deactivate the host
174 */
175 void terminate_connection(connection_t *c, int report)
176 {
177         cp();
178
179         if(c->status.remove)
180                 return;
181
182         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Closing connection with %s (%s)"),
183                            c->name, c->hostname);
184
185         c->status.remove = 1;
186         c->status.active = 0;
187
188         if(c->node)
189                 c->node->connection = NULL;
190
191         if(c->socket)
192                 close(c->socket);
193
194         if(c->edge) {
195                 if(report)
196                         send_del_edge(broadcast, c->edge);
197
198                 edge_del(c->edge);
199
200                 /* Run MST and SSSP algorithms */
201
202                 graph();
203         }
204
205         /* Check if this was our outgoing connection */
206
207         if(c->outgoing) {
208                 retry_outgoing(c->outgoing);
209                 c->outgoing = NULL;
210         }
211 }
212
213 /*
214   Check if the other end is active.
215   If we have sent packets, but didn't receive any,
216   then possibly the other end is dead. We send a
217   PING request over the meta connection. If the other
218   end does not reply in time, we consider them dead
219   and close the connection.
220 */
221 static void check_dead_connections(void)
222 {
223         avl_node_t *node, *next;
224         connection_t *c;
225
226         cp();
227
228         for(node = connection_tree->head; node; node = next) {
229                 next = node->next;
230                 c = (connection_t *) 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"),
236                                                            c->name, c->hostname);
237                                         c->status.timeout = 1;
238                                         terminate_connection(c, 1);
239                                 } else {
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, 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                                 terminate_connection(c, 0);
252                         }
253                 }
254         }
255 }
256
257 /*
258   check all connections to see if anything
259   happened on their sockets
260 */
261 static void check_network_activity(fd_set * f)
262 {
263         connection_t *c;
264         avl_node_t *node;
265         int result, i;
266         int len = sizeof(result);
267         vpn_packet_t packet;
268
269         cp();
270
271         if(FD_ISSET(device_fd, f)) {
272                 if(!read_packet(&packet))
273                         route_outgoing(&packet);
274         }
275
276         for(node = connection_tree->head; node; node = node->next) {
277                 c = (connection_t *) node->data;
278
279                 if(c->status.remove)
280                         continue;
281
282                 if(FD_ISSET(c->socket, f)) {
283                         if(c->status.connecting) {
284                                 c->status.connecting = 0;
285                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, &result, &len);
286
287                                 if(!result)
288                                         finish_connecting(c);
289                                 else {
290                                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
291                                                            _("Error while connecting to %s (%s): %s"),
292                                                            c->name, c->hostname, strerror(result));
293                                         close(c->socket);
294                                         do_outgoing_connection(c);
295                                         continue;
296                                 }
297                         }
298
299                         if(receive_meta(c) < 0) {
300                                 terminate_connection(c, c->status.active);
301                                 continue;
302                         }
303                 }
304         }
305
306         for(i = 0; i < listen_sockets; i++) {
307                 if(FD_ISSET(listen_socket[i].udp, f))
308                         handle_incoming_vpn_data(listen_socket[i].udp);
309
310                 if(FD_ISSET(listen_socket[i].tcp, f))
311                         handle_new_meta_connection(listen_socket[i].tcp);
312         }
313 }
314
315 /*
316   this is where it all happens...
317 */
318 void main_loop(void)
319 {
320         fd_set fset;
321         struct timeval tv;
322         int r, maxfd;
323         time_t last_ping_check, last_config_check;
324         event_t *event;
325
326         cp();
327
328         last_ping_check = now;
329         last_config_check = now;
330         srand(now);
331
332         for(;;) {
333                 now = time(NULL);
334
335                 tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
336                 tv.tv_usec = 0;
337
338                 maxfd = build_fdset(&fset);
339
340                 r = select(maxfd + 1, &fset, NULL, NULL, &tv);
341
342                 if(r < 0) {
343                         if(errno != EINTR && errno != EAGAIN) {
344                                 logger(LOG_ERR, _("Error while waiting for input: %s"),
345                                            strerror(errno));
346                                 cp_trace();
347                                 dump_connections();
348                                 return;
349                         }
350
351                         continue;
352                 }
353
354                 check_network_activity(&fset);
355
356                 if(do_purge) {
357                         purge();
358                         do_purge = 0;
359                 }
360
361                 /* Let's check if everybody is still alive */
362
363                 if(last_ping_check + pingtimeout < now) {
364                         check_dead_connections();
365                         last_ping_check = now;
366
367                         if(routing_mode == RMODE_SWITCH)
368                                 age_mac();
369
370                         age_past_requests();
371
372                         /* Should we regenerate our key? */
373
374                         if(keyexpires < now) {
375                                 ifdebug(STATUS) logger(LOG_INFO, _("Regenerating symmetric key"));
376
377                                 RAND_pseudo_bytes(myself->key, myself->keylength);
378                                 EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, myself->key, myself->key + myself->cipher->key_len);
379                                 send_key_changed(broadcast, myself);
380                                 keyexpires = now + keylifetime;
381                         }
382                 }
383
384
385                 while((event = get_expired_event())) {
386                         event->handler(event->data);
387                         free(event);
388                 }
389
390                 if(sigalrm) {
391                         logger(LOG_INFO, _("Flushing event queue"));
392
393                         while(event_tree->head) {
394                                 event = (event_t *) event_tree->head->data;
395                                 event->handler(event->data);
396                                 event_del(event);
397                         }
398                         sigalrm = 0;
399                 }
400
401                 if(sighup) {
402                         connection_t *c;
403                         avl_node_t *node;
404                         char *fname;
405                         struct stat s;
406                         
407                         sighup = 0;
408                         
409                         /* Reread our own configuration file */
410
411                         exit_configuration(&config_tree);
412                         init_configuration(&config_tree);
413
414                         if(read_server_config()) {
415                                 logger(LOG_ERR, _("Unable to reread configuration file, exitting."));
416                                 exit(1);
417                         }
418
419                         /* Close connections to hosts that have a changed or deleted host config file */
420                         
421                         for(node = connection_tree->head; node; node = node->next) {
422                                 c = (connection_t *) node->data;
423                                 
424                                 if(c->outgoing) {
425                                         free(c->outgoing->name);
426                                         freeaddrinfo(c->outgoing->ai);
427                                         free(c->outgoing);
428                                         c->outgoing = NULL;
429                                 }
430                                 
431                                 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
432                                 if(stat(fname, &s) || s.st_mtime > last_config_check)
433                                         terminate_connection(c, c->status.active);
434                                 free(fname);
435                         }
436
437                         last_config_check = now;
438
439                         /* Try to make outgoing connections */
440                         
441                         try_outgoing_connections();
442                                                 
443                         continue;
444                 }
445         }
446 }