Native Windows support.
[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.195 2003/07/29 22:59:00 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 #include "xalloc.h"
43
44 bool do_purge = false;
45
46 time_t now = 0;
47
48 /* Purge edges and subnets of unreachable nodes. Use carefully. */
49
50 static void purge(void)
51 {
52         avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
53         node_t *n;
54         edge_t *e;
55         subnet_t *s;
56
57         cp();
58
59         ifdebug(PROTOCOL) logger(LOG_DEBUG, _("Purging unreachable nodes"));
60
61         for(nnode = node_tree->head; nnode; nnode = nnext) {
62                 nnext = nnode->next;
63                 n = (node_t *) 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 = (subnet_t *) snode->data;
72                                 send_del_subnet(broadcast, s);
73                                 subnet_del(n, s);
74                         }
75
76                         for(enode = n->edge_tree->head; enode; enode = enext) {
77                                 enext = enode->next;
78                                 e = (edge_t *) enode->data;
79                                 send_del_edge(broadcast, e);
80                                 edge_del(e);
81                         }
82
83                         node_del(n);
84                 }
85         }
86 }
87
88 /*
89   put all file descriptors in an fd_set array
90   While we're at it, purge stuff that needs to be removed.
91 */
92 static int build_fdset(fd_set * fs)
93 {
94         avl_node_t *node, *next;
95         connection_t *c;
96         int i, max = 0;
97
98         cp();
99
100         FD_ZERO(fs);
101
102         for(node = connection_tree->head; node; node = next) {
103                 next = node->next;
104                 c = (connection_t *) node->data;
105
106                 if(c->status.remove) {
107                         connection_del(c);
108                         if(!connection_tree->head)
109                                 purge();
110                 } else {
111                         FD_SET(c->socket, fs);
112                         if(c->socket > max)
113                                 max = c->socket;
114                 }
115         }
116
117         for(i = 0; i < listen_sockets; i++) {
118                 FD_SET(listen_socket[i].tcp, fs);
119                 if(listen_socket[i].tcp > max)
120                         max = listen_socket[i].tcp;
121                 FD_SET(listen_socket[i].udp, fs);
122                 if(listen_socket[i].udp > max)
123                         max = listen_socket[i].udp;
124         }
125
126         FD_SET(device_fd, fs);
127         if(device_fd > max)
128                 max = device_fd;
129         
130         return max;
131 }
132
133 /*
134   Terminate a connection:
135   - Close the socket
136   - Remove associated edge and tell other connections about it if report = true
137   - Check if we need to retry making an outgoing connection
138   - Deactivate the host
139 */
140 void terminate_connection(connection_t *c, bool report)
141 {
142         cp();
143
144         if(c->status.remove)
145                 return;
146
147         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Closing connection with %s (%s)"),
148                            c->name, c->hostname);
149
150         c->status.remove = true;
151         c->status.active = false;
152
153         if(c->node)
154                 c->node->connection = NULL;
155
156         if(c->socket)
157                 closesocket(c->socket);
158
159         if(c->edge) {
160                 if(report)
161                         send_del_edge(broadcast, c->edge);
162
163                 edge_del(c->edge);
164
165                 /* Run MST and SSSP algorithms */
166
167                 graph();
168         }
169
170         /* Check if this was our outgoing connection */
171
172         if(c->outgoing) {
173                 retry_outgoing(c->outgoing);
174                 c->outgoing = NULL;
175         }
176 }
177
178 /*
179   Check if the other end is active.
180   If we have sent packets, but didn't receive any,
181   then possibly the other end is dead. We send a
182   PING request over the meta connection. If the other
183   end does not reply in time, we consider them dead
184   and close the connection.
185 */
186 static void check_dead_connections(void)
187 {
188         avl_node_t *node, *next;
189         connection_t *c;
190
191         cp();
192
193         for(node = connection_tree->head; node; node = next) {
194                 next = node->next;
195                 c = (connection_t *) node->data;
196
197                 if(c->last_ping_time + pingtimeout < now) {
198                         if(c->status.active) {
199                                 if(c->status.pinged) {
200                                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("%s (%s) didn't respond to PING"),
201                                                            c->name, c->hostname);
202                                         c->status.timeout = true;
203                                         terminate_connection(c, true);
204                                 } else {
205                                         send_ping(c);
206                                 }
207                         } else {
208                                 if(c->status.remove) {
209                                         logger(LOG_WARNING, _("Old connection_t for %s (%s) status %04x still lingering, deleting..."),
210                                                    c->name, c->hostname, *(uint32_t *)&c->status);
211                                         connection_del(c);
212                                         continue;
213                                 }
214                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
215                                                    c->name, c->hostname);
216                                 terminate_connection(c, false);
217                         }
218                 }
219         }
220 }
221
222 /*
223   check all connections to see if anything
224   happened on their sockets
225 */
226 static void check_network_activity(fd_set * f)
227 {
228         connection_t *c;
229         avl_node_t *node;
230         int result, i;
231         int len = sizeof(result);
232         vpn_packet_t packet;
233
234         cp();
235
236         if(FD_ISSET(device_fd, f)) {
237                 if(read_packet(&packet))
238                         route_outgoing(&packet);
239         }
240
241         for(node = connection_tree->head; node; node = node->next) {
242                 c = (connection_t *) node->data;
243
244                 if(c->status.remove)
245                         continue;
246
247                 if(FD_ISSET(c->socket, f)) {
248                         if(c->status.connecting) {
249                                 c->status.connecting = false;
250                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, &result, &len);
251
252                                 if(!result)
253                                         finish_connecting(c);
254                                 else {
255                                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
256                                                            _("Error while connecting to %s (%s): %s"),
257                                                            c->name, c->hostname, strerror(result));
258                                         closesocket(c->socket);
259                                         do_outgoing_connection(c);
260                                         continue;
261                                 }
262                         }
263
264                         if(!receive_meta(c)) {
265                                 terminate_connection(c, c->status.active);
266                                 continue;
267                         }
268                 }
269         }
270
271         for(i = 0; i < listen_sockets; i++) {
272                 if(FD_ISSET(listen_socket[i].udp, f))
273                         handle_incoming_vpn_data(listen_socket[i].udp);
274
275                 if(FD_ISSET(listen_socket[i].tcp, f))
276                         handle_new_meta_connection(listen_socket[i].tcp);
277         }
278 }
279
280 /*
281   this is where it all happens...
282 */
283 void main_loop(void)
284 {
285         fd_set fset;
286         struct timeval tv;
287         int r, maxfd;
288         time_t last_ping_check, last_config_check;
289         event_t *event;
290
291         cp();
292
293         last_ping_check = now;
294         last_config_check = now;
295         srand(now);
296
297         for(;;) {
298                 now = time(NULL);
299
300                 tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
301                 tv.tv_usec = 0;
302
303                 maxfd = build_fdset(&fset);
304
305                 r = select(maxfd + 1, &fset, NULL, NULL, &tv);
306
307                 if(r < 0) {
308                         if(errno != EINTR && errno != EAGAIN) {
309                                 logger(LOG_ERR, _("Error while waiting for input: %s"),
310                                            strerror(errno));
311                                 cp_trace();
312                                 dump_connections();
313                                 return;
314                         }
315
316                         continue;
317                 }
318
319                 check_network_activity(&fset);
320
321                 if(do_purge) {
322                         purge();
323                         do_purge = false;
324                 }
325
326                 /* Let's check if everybody is still alive */
327
328                 if(last_ping_check + pingtimeout < now) {
329                         check_dead_connections();
330                         last_ping_check = now;
331
332                         if(routing_mode == RMODE_SWITCH)
333                                 age_mac();
334
335                         age_past_requests();
336
337                         /* Should we regenerate our key? */
338
339                         if(keyexpires < now) {
340                                 ifdebug(STATUS) logger(LOG_INFO, _("Regenerating symmetric key"));
341
342                                 RAND_pseudo_bytes(myself->key, myself->keylength);
343                                 if(myself->cipher)
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 = false;
365                 }
366
367                 if(sighup) {
368                         connection_t *c;
369                         avl_node_t *node;
370                         char *fname;
371                         struct stat s;
372                         
373                         sighup = false;
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 }