Big header file cleanup: everything that has to do with standard system
[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.191 2003/07/17 15:06:26 guus Exp $
21 */
22
23 #include "system.h"
24
25 #include <openssl/rand.h>
26
27 #include "utils.h"
28 #include "avl_tree.h"
29 #include "conf.h"
30 #include "connection.h"
31 #include "device.h"
32 #include "event.h"
33 #include "graph.h"
34 #include "logger.h"
35 #include "meta.h"
36 #include "net.h"
37 #include "netutl.h"
38 #include "process.h"
39 #include "protocol.h"
40 #include "route.h"
41 #include "subnet.h"
42
43 int do_purge = 0;
44 int sighup = 0;
45 int sigalrm = 0;
46
47 time_t now = 0;
48
49 /* Purge edges and subnets of unreachable nodes. Use carefully. */
50
51 static void purge(void)
52 {
53         avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
54         node_t *n;
55         edge_t *e;
56         subnet_t *s;
57
58         cp();
59
60         ifdebug(PROTOCOL) logger(LOG_DEBUG, _("Purging unreachable nodes"));
61
62         for(nnode = node_tree->head; nnode; nnode = nnext) {
63                 nnext = nnode->next;
64                 n = (node_t *) 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 = (subnet_t *) snode->data;
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 = (edge_t *) enode->data;
80                                 send_del_edge(broadcast, e);
81                                 edge_del(e);
82                         }
83
84                         node_del(n);
85                 }
86         }
87 }
88
89 /*
90   put all file descriptors in an fd_set array
91   While we're at it, purge stuff that needs to be removed.
92 */
93 static int build_fdset(fd_set * fs)
94 {
95         avl_node_t *node, *next;
96         connection_t *c;
97         int i, max = 0;
98
99         cp();
100
101         FD_ZERO(fs);
102
103         for(node = connection_tree->head; node; node = next) {
104                 next = node->next;
105                 c = (connection_t *) node->data;
106
107                 if(c->status.remove) {
108                         connection_del(c);
109                         if(!connection_tree->head)
110                                 purge();
111                 } else {
112                         FD_SET(c->socket, fs);
113                         if(c->socket > max)
114                                 max = c->socket;
115                 }
116         }
117
118         for(i = 0; i < listen_sockets; i++) {
119                 FD_SET(listen_socket[i].tcp, fs);
120                 if(listen_socket[i].tcp > max)
121                         max = listen_socket[i].tcp;
122                 FD_SET(listen_socket[i].udp, fs);
123                 if(listen_socket[i].udp > max)
124                         max = listen_socket[i].udp;
125         }
126
127         FD_SET(device_fd, fs);
128         if(device_fd > max)
129                 max = device_fd;
130         
131         return max;
132 }
133
134 /*
135   Terminate a connection:
136   - Close the socket
137   - Remove associated edge and tell other connections about it if report = 1
138   - Check if we need to retry making an outgoing connection
139   - Deactivate the host
140 */
141 void terminate_connection(connection_t *c, int report)
142 {
143         cp();
144
145         if(c->status.remove)
146                 return;
147
148         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Closing connection with %s (%s)"),
149                            c->name, c->hostname);
150
151         c->status.remove = 1;
152         c->status.active = 0;
153
154         if(c->node)
155                 c->node->connection = NULL;
156
157         if(c->socket)
158                 close(c->socket);
159
160         if(c->edge) {
161                 if(report)
162                         send_del_edge(broadcast, c->edge);
163
164                 edge_del(c->edge);
165
166                 /* Run MST and SSSP algorithms */
167
168                 graph();
169         }
170
171         /* Check if this was our outgoing connection */
172
173         if(c->outgoing) {
174                 retry_outgoing(c->outgoing);
175                 c->outgoing = NULL;
176         }
177 }
178
179 /*
180   Check if the other end is active.
181   If we have sent packets, but didn't receive any,
182   then possibly the other end is dead. We send a
183   PING request over the meta connection. If the other
184   end does not reply in time, we consider them dead
185   and close the connection.
186 */
187 static void check_dead_connections(void)
188 {
189         avl_node_t *node, *next;
190         connection_t *c;
191
192         cp();
193
194         for(node = connection_tree->head; node; node = next) {
195                 next = node->next;
196                 c = (connection_t *) node->data;
197
198                 if(c->last_ping_time + pingtimeout < now) {
199                         if(c->status.active) {
200                                 if(c->status.pinged) {
201                                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("%s (%s) didn't respond to PING"),
202                                                            c->name, c->hostname);
203                                         c->status.timeout = 1;
204                                         terminate_connection(c, 1);
205                                 } else {
206                                         send_ping(c);
207                                 }
208                         } else {
209                                 if(c->status.remove) {
210                                         logger(LOG_WARNING, _("Old connection_t for %s (%s) status %04x still lingering, deleting..."),
211                                                    c->name, c->hostname, c->status);
212                                         connection_del(c);
213                                         continue;
214                                 }
215                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
216                                                    c->name, c->hostname);
217                                 terminate_connection(c, 0);
218                         }
219                 }
220         }
221 }
222
223 /*
224   check all connections to see if anything
225   happened on their sockets
226 */
227 static void check_network_activity(fd_set * f)
228 {
229         connection_t *c;
230         avl_node_t *node;
231         int result, i;
232         int len = sizeof(result);
233         vpn_packet_t packet;
234
235         cp();
236
237         if(FD_ISSET(device_fd, f)) {
238                 if(!read_packet(&packet))
239                         route_outgoing(&packet);
240         }
241
242         for(node = connection_tree->head; node; node = node->next) {
243                 c = (connection_t *) node->data;
244
245                 if(c->status.remove)
246                         continue;
247
248                 if(FD_ISSET(c->socket, f)) {
249                         if(c->status.connecting) {
250                                 c->status.connecting = 0;
251                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, &result, &len);
252
253                                 if(!result)
254                                         finish_connecting(c);
255                                 else {
256                                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
257                                                            _("Error while connecting to %s (%s): %s"),
258                                                            c->name, c->hostname, strerror(result));
259                                         close(c->socket);
260                                         do_outgoing_connection(c);
261                                         continue;
262                                 }
263                         }
264
265                         if(receive_meta(c) < 0) {
266                                 terminate_connection(c, c->status.active);
267                                 continue;
268                         }
269                 }
270         }
271
272         for(i = 0; i < listen_sockets; i++) {
273                 if(FD_ISSET(listen_socket[i].udp, f))
274                         handle_incoming_vpn_data(listen_socket[i].udp);
275
276                 if(FD_ISSET(listen_socket[i].tcp, f))
277                         handle_new_meta_connection(listen_socket[i].tcp);
278         }
279 }
280
281 /*
282   this is where it all happens...
283 */
284 void main_loop(void)
285 {
286         fd_set fset;
287         struct timeval tv;
288         int r, maxfd;
289         time_t last_ping_check, last_config_check;
290         event_t *event;
291
292         cp();
293
294         last_ping_check = now;
295         last_config_check = now;
296         srand(now);
297
298         for(;;) {
299                 now = time(NULL);
300
301                 tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
302                 tv.tv_usec = 0;
303
304                 maxfd = build_fdset(&fset);
305
306                 r = select(maxfd + 1, &fset, NULL, NULL, &tv);
307
308                 if(r < 0) {
309                         if(errno != EINTR && errno != EAGAIN) {
310                                 logger(LOG_ERR, _("Error while waiting for input: %s"),
311                                            strerror(errno));
312                                 cp_trace();
313                                 dump_connections();
314                                 return;
315                         }
316
317                         continue;
318                 }
319
320                 check_network_activity(&fset);
321
322                 if(do_purge) {
323                         purge();
324                         do_purge = 0;
325                 }
326
327                 /* Let's check if everybody is still alive */
328
329                 if(last_ping_check + pingtimeout < now) {
330                         check_dead_connections();
331                         last_ping_check = now;
332
333                         if(routing_mode == RMODE_SWITCH)
334                                 age_mac();
335
336                         age_past_requests();
337
338                         /* Should we regenerate our key? */
339
340                         if(keyexpires < now) {
341                                 ifdebug(STATUS) logger(LOG_INFO, _("Regenerating symmetric key"));
342
343                                 RAND_pseudo_bytes(myself->key, myself->keylength);
344                                 EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, myself->key, myself->key + myself->cipher->key_len);
345                                 send_key_changed(broadcast, myself);
346                                 keyexpires = now + keylifetime;
347                         }
348                 }
349
350
351                 while((event = get_expired_event())) {
352                         event->handler(event->data);
353                         free(event);
354                 }
355
356                 if(sigalrm) {
357                         logger(LOG_INFO, _("Flushing event queue"));
358
359                         while(event_tree->head) {
360                                 event = (event_t *) event_tree->head->data;
361                                 event->handler(event->data);
362                                 event_del(event);
363                         }
364                         sigalrm = 0;
365                 }
366
367                 if(sighup) {
368                         connection_t *c;
369                         avl_node_t *node;
370                         char *fname;
371                         struct stat s;
372                         
373                         sighup = 0;
374                         
375                         /* Reread our own configuration file */
376
377                         exit_configuration(&config_tree);
378                         init_configuration(&config_tree);
379
380                         if(read_server_config()) {
381                                 logger(LOG_ERR, _("Unable to reread configuration file, exitting."));
382                                 exit(1);
383                         }
384
385                         /* Close connections to hosts that have a changed or deleted host config file */
386                         
387                         for(node = connection_tree->head; node; node = node->next) {
388                                 c = (connection_t *) node->data;
389                                 
390                                 if(c->outgoing) {
391                                         free(c->outgoing->name);
392                                         freeaddrinfo(c->outgoing->ai);
393                                         free(c->outgoing);
394                                         c->outgoing = NULL;
395                                 }
396                                 
397                                 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
398                                 if(stat(fname, &s) || s.st_mtime > last_config_check)
399                                         terminate_connection(c, c->status.active);
400                                 free(fname);
401                         }
402
403                         last_config_check = now;
404
405                         /* Try to make outgoing connections */
406                         
407                         try_outgoing_connections();
408                                                 
409                         continue;
410                 }
411         }
412 }