Merging of the entire pre5 branch.
[oweals/tinc.git] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998-2002 Ivo Timmermans <itimmermans@bigfoot.com>,
4                   2000-2002 Guus Sliepen <guus@sliepen.warande.net>
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.152 2002/02/10 21:57:54 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <netdb.h>
28 #include <netinet/in.h>
29 #ifdef HAVE_LINUX
30  #include <netinet/ip.h>
31  #include <netinet/tcp.h>
32 #endif
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <signal.h>
37 #include <sys/signal.h>
38 #include <sys/time.h>
39 #include <sys/types.h>
40 #include <syslog.h>
41 #include <unistd.h>
42 #include <sys/ioctl.h>
43 /* SunOS really wants sys/socket.h BEFORE net/if.h,
44    and FreeBSD wants these lines below the rest. */
45 #include <arpa/inet.h>
46 #include <sys/socket.h>
47 #include <net/if.h>
48
49 #include <openssl/rand.h>
50 #include <openssl/evp.h>
51 #include <openssl/pem.h>
52 #include <openssl/hmac.h>
53
54 #ifndef HAVE_RAND_PSEUDO_BYTES
55 #define RAND_pseudo_bytes RAND_bytes
56 #endif
57
58 #include <utils.h>
59 #include <xalloc.h>
60 #include <avl_tree.h>
61 #include <list.h>
62
63 #include "conf.h"
64 #include "connection.h"
65 #include "meta.h"
66 #include "net.h"
67 #include "netutl.h"
68 #include "process.h"
69 #include "protocol.h"
70 #include "subnet.h"
71 #include "graph.h"
72 #include "process.h"
73 #include "route.h"
74 #include "device.h"
75 #include "event.h"
76
77 #include "system.h"
78
79 int maxtimeout = 900;
80 int seconds_till_retry = 5;
81
82 int tcp_socket = -1;
83 int udp_socket = -1;
84
85 int keylifetime = 0;
86 int keyexpires = 0;
87
88 int do_prune = 0;
89 int do_purge = 0;
90 int sighup = 0;
91 int sigalrm = 0;
92
93 #define MAX_SEQNO 1073741824
94
95 /* VPN packet I/O */
96
97 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
98 {
99   vpn_packet_t outpkt;
100   int outlen, outpad;
101   EVP_CIPHER_CTX ctx;
102   char hmac[EVP_MAX_MD_SIZE];
103 cp
104
105   if(myself->digest && myself->maclength)
106     {
107       inpkt->len -= myself->maclength;
108       HMAC(myself->digest, myself->key, myself->keylength, (char *)&inpkt->seqno, inpkt->len, hmac, NULL);
109       if(memcmp(hmac, (char *)&inpkt->seqno + inpkt->len, myself->maclength))
110         {
111           syslog(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"), n->name, n->hostname);
112           return;
113         }
114     }
115
116   /* Decrypt the packet */
117
118   if(myself->cipher)
119   {
120     EVP_DecryptInit(&ctx, myself->cipher, myself->key, myself->key + myself->cipher->key_len);
121     EVP_DecryptUpdate(&ctx, (char *)&outpkt.seqno, &outlen, (char *)&inpkt->seqno, inpkt->len);
122     EVP_DecryptFinal(&ctx, (char *)&outpkt.seqno + outlen, &outpad);
123     outlen += outpad;
124     outpkt.len = outlen - sizeof(outpkt.seqno);
125   }
126   else
127   {
128     memcpy((char *)&outpkt.seqno, (char *)&inpkt->seqno, inpkt->len);
129     outpkt.len = inpkt->len - sizeof(outpkt.seqno);
130   }
131
132   if (ntohl(outpkt.seqno) <= n->received_seqno)
133   {
134     syslog(LOG_DEBUG, _("Got late or replayed packet from %s (%s), seqno %d"), n->name, n->hostname, ntohl(*(unsigned int *)&outpkt.seqno));
135     return;
136   }
137   
138   n->received_seqno = ntohl(outpkt.seqno);
139
140   if(n->received_seqno > MAX_SEQNO)
141     keyexpires = 0;
142
143   receive_packet(n, &outpkt);
144 cp
145 }
146
147 void receive_tcppacket(connection_t *c, char *buffer, int len)
148 {
149   vpn_packet_t outpkt;
150 cp
151   outpkt.len = len;
152   memcpy(outpkt.data, buffer, len);
153
154   receive_packet(c->node, &outpkt);
155 cp
156 }
157
158 void receive_packet(node_t *n, vpn_packet_t *packet)
159 {
160 cp
161   if(debug_lvl >= DEBUG_TRAFFIC)
162     syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, n->name, n->hostname);
163
164   route_incoming(n, packet);
165 cp
166 }
167
168 void send_udppacket(node_t *n, vpn_packet_t *inpkt)
169 {
170   vpn_packet_t outpkt;
171   int outlen, outpad;
172   EVP_CIPHER_CTX ctx;
173   struct sockaddr_in to;
174   socklen_t tolen = sizeof(to);
175   vpn_packet_t *copy;
176 cp
177   if(!n->status.validkey)
178     {
179       if(debug_lvl >= DEBUG_TRAFFIC)
180         syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
181                n->name, n->hostname);
182
183       /* Since packet is on the stack of handle_tap_input(),
184          we have to make a copy of it first. */
185
186       copy = xmalloc(sizeof(vpn_packet_t));
187       memcpy(copy, inpkt, sizeof(vpn_packet_t));
188
189       list_insert_tail(n->queue, copy);
190
191       if(!n->status.waitingforkey)
192         send_req_key(n->nexthop->connection, myself, n);
193       return;
194     }
195
196   /* Encrypt the packet. */
197
198   inpkt->seqno = htonl(++(n->sent_seqno));
199
200   if(n->cipher)
201   {
202     EVP_EncryptInit(&ctx, n->cipher, n->key, n->key + n->cipher->key_len);
203     EVP_EncryptUpdate(&ctx, (char *)&outpkt.seqno, &outlen, (char *)&inpkt->seqno, inpkt->len + sizeof(inpkt->seqno));
204     EVP_EncryptFinal(&ctx, (char *)&outpkt.seqno + outlen, &outpad);
205     outlen += outpad;
206   }
207   else
208   {
209     memcpy((char *)&outpkt.seqno, (char *)&inpkt->seqno, inpkt->len + sizeof(inpkt->seqno));
210     outlen = inpkt->len + sizeof(inpkt->seqno);
211   }
212
213   if(n->digest && n->maclength)
214     {
215       HMAC(n->digest, n->key, n->keylength, (char *)&outpkt.seqno, outlen, (char *)&outpkt.seqno + outlen, &outpad);
216       outlen += n->maclength;
217     }
218
219   to.sin_family = AF_INET;
220   to.sin_addr.s_addr = htonl(n->address);
221   to.sin_port = htons(n->port);
222
223   if((sendto(udp_socket, (char *)&outpkt.seqno, outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
224     {
225       syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
226              n->name, n->hostname);
227       return;
228     }
229 cp
230 }
231
232 /*
233   send a packet to the given vpn ip.
234 */
235 void send_packet(node_t *n, vpn_packet_t *packet)
236 {
237   node_t *via;
238 cp
239   if(debug_lvl >= DEBUG_TRAFFIC)
240     syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
241            packet->len, n->name, n->hostname);
242
243   if(n == myself)
244     {
245       if(debug_lvl >= DEBUG_TRAFFIC)
246         {
247           syslog(LOG_NOTICE, _("Packet is looping back to us!"));
248         }
249
250       return;
251     }
252  
253   if(!n->status.reachable)
254     {
255       if(debug_lvl >= DEBUG_TRAFFIC)
256         syslog(LOG_INFO, _("Node %s (%s) is not reachable"),
257                n->name, n->hostname);
258       return;
259     }
260
261   via = (n->via == myself)?n->nexthop:n->via;
262
263   if(via != n && debug_lvl >= DEBUG_TRAFFIC)
264     syslog(LOG_ERR, _("Sending packet to %s via %s (%s)"),
265            n->name, via->name, n->via->hostname);
266
267   if((myself->options | via->options) & OPTION_TCPONLY)
268     {
269       if(send_tcppacket(via->connection, packet))
270         terminate_connection(via->connection, 1);
271     }
272   else
273     send_udppacket(via, packet);
274 }
275
276 /* Broadcast a packet using the minimum spanning tree */
277
278 void broadcast_packet(node_t *from, vpn_packet_t *packet)
279 {
280   avl_node_t *node;
281   connection_t *c;
282 cp
283   if(debug_lvl >= DEBUG_TRAFFIC)
284     syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
285            packet->len, from->name, from->hostname);
286
287   for(node = connection_tree->head; node; node = node->next)
288     {
289       c = (connection_t *)node->data;
290       if(c->status.active && c->status.mst && c != from->nexthop->connection)
291         send_packet(c->node, packet);
292     }
293 cp
294 }
295
296 void flush_queue(node_t *n)
297 {
298   list_node_t *node, *next;
299 cp
300   if(debug_lvl >= DEBUG_TRAFFIC)
301     syslog(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
302
303   for(node = n->queue->head; node; node = next)
304     {
305       next = node->next;
306       send_udppacket(n, (vpn_packet_t *)node->data);
307       list_delete_node(n->queue, node);
308     }
309 cp
310 }
311
312 /* Setup sockets */
313
314 int setup_listen_socket(port_t port)
315 {
316   int nfd, flags;
317   struct sockaddr_in a;
318   int option;
319   ipv4_t *address;
320 #ifdef HAVE_LINUX
321   char *interface;
322 #endif
323 cp
324   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
325     {
326       syslog(LOG_ERR, _("Creating metasocket failed: %m"));
327       return -1;
328     }
329
330   flags = fcntl(nfd, F_GETFL);
331   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
332     {
333       close(nfd);
334       syslog(LOG_ERR, _("System call `%s' failed: %m"),
335              "fcntl");
336       return -1;
337     }
338
339   /* Optimize TCP settings */
340
341   option = 1;
342   setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
343   setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
344 #ifdef HAVE_LINUX
345   setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
346
347   option = IPTOS_LOWDELAY;
348   setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
349
350   if(get_config_string(lookup_config(config_tree, "BindToInterface"), &interface))
351     if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)))
352       {
353         close(nfd);
354         syslog(LOG_ERR, _("Can't bind to interface %s: %m"), interface);
355         return -1;
356       }
357 #endif
358
359   memset(&a, 0, sizeof(a));
360   a.sin_family = AF_INET;
361   a.sin_addr.s_addr = htonl(INADDR_ANY);
362   a.sin_port = htons(port);
363
364   if(get_config_address(lookup_config(config_tree, "BindToAddress"), &address))
365     {
366       a.sin_addr.s_addr = htonl(*address);
367       free(address);
368     }
369
370   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
371     {
372       close(nfd);
373       syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
374       return -1;
375     }
376
377   if(listen(nfd, 3))
378     {
379       close(nfd);
380       syslog(LOG_ERR, _("System call `%s' failed: %m"),
381              "listen");
382       return -1;
383     }
384 cp
385   return nfd;
386 }
387
388 int setup_vpn_in_socket(port_t port)
389 {
390   int nfd, flags;
391   struct sockaddr_in a;
392   const int one = 1;
393 cp
394   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
395     {
396       close(nfd);
397       syslog(LOG_ERR, _("Creating socket failed: %m"));
398       return -1;
399     }
400
401   setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
402
403   flags = fcntl(nfd, F_GETFL);
404   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
405     {
406       close(nfd);
407       syslog(LOG_ERR, _("System call `%s' failed: %m"),
408              "fcntl");
409       return -1;
410     }
411
412   memset(&a, 0, sizeof(a));
413   a.sin_family = AF_INET;
414   a.sin_port = htons(port);
415   a.sin_addr.s_addr = htonl(INADDR_ANY);
416
417   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
418     {
419       close(nfd);
420       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
421       return -1;
422     }
423 cp
424   return nfd;
425 }
426
427 void retry_outgoing(outgoing_t *outgoing)
428 {
429   event_t *event;
430 cp
431   outgoing->timeout += 5;
432   if(outgoing->timeout > maxtimeout)
433     outgoing->timeout = maxtimeout;
434
435   event = new_event();
436   event->handler = (event_handler_t)setup_outgoing_connection;
437   event->time = time(NULL) + outgoing->timeout;
438   event->data = outgoing;
439   event_add(event);
440
441   if(debug_lvl >= DEBUG_CONNECTIONS)
442     syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), outgoing->timeout);
443 cp
444 }
445
446 int setup_outgoing_socket(connection_t *c)
447 {
448   int flags;
449   struct sockaddr_in a;
450 cp
451   if(debug_lvl >= DEBUG_CONNECTIONS)
452     syslog(LOG_INFO, _("Trying to connect to %s (%s)"), c->name, c->hostname);
453
454   c->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
455
456   if(c->socket == -1)
457     {
458       syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
459              c->hostname, c->port);
460       return -1;
461     }
462
463   /* Bind first to get a fix on our source port???
464
465   a.sin_family = AF_INET;
466   a.sin_port = htons(0);
467   a.sin_addr.s_addr = htonl(INADDR_ANY);
468
469   if(bind(c->socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
470     {
471       close(c->socket);
472       syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
473       return -1;
474     }
475
476   */
477
478   /* Optimize TCP settings?
479
480   option = 1;
481   setsockopt(c->socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
482 #ifdef HAVE_LINUX
483   setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
484
485   option = IPTOS_LOWDELAY;
486   setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof(option));
487 #endif
488
489   */
490
491   /* Connect */
492
493   a.sin_family = AF_INET;
494   a.sin_port = htons(c->port);
495   a.sin_addr.s_addr = htonl(c->address);
496
497   if(connect(c->socket, (struct sockaddr *)&a, sizeof(a)) == -1)
498     {
499       close(c->socket);
500       syslog(LOG_ERR, _("%s port %hd: %m"), c->hostname, c->port);
501       return -1;
502     }
503
504   flags = fcntl(c->socket, F_GETFL);
505
506   if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0)
507     {
508       close(c->socket);
509       syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
510              c->hostname, c->port);
511       return -1;
512     }
513
514   if(debug_lvl >= DEBUG_CONNECTIONS)
515     syslog(LOG_INFO, _("Connected to %s port %hd"),
516          c->hostname, c->port);
517 cp
518   return 0;
519 }
520
521 void setup_outgoing_connection(outgoing_t *outgoing)
522 {
523   connection_t *c;
524   node_t *n;
525   struct hostent *h;
526 cp
527   n = lookup_node(outgoing->name);
528   
529   if(n)
530     if(n->connection)
531       {
532         if(debug_lvl >= DEBUG_CONNECTIONS)       
533           syslog(LOG_INFO, _("Already connected to %s"), outgoing->name);
534         n->connection->outgoing = outgoing;
535         return;
536       }
537
538   c = new_connection();
539   c->name = xstrdup(outgoing->name);
540
541   init_configuration(&c->config_tree);
542   read_connection_config(c);
543   
544   if(!get_config_string(lookup_config(c->config_tree, "Address"), &c->hostname))
545     {
546       syslog(LOG_ERR, _("No address specified for %s"), c->name);
547       free_connection(c);
548       free(outgoing->name);
549       free(outgoing);
550       return;
551     }
552
553   if(!get_config_port(lookup_config(c->config_tree, "Port"), &c->port))
554     c->port = 655;
555
556   if(!(h = gethostbyname(c->hostname)))
557     {
558       syslog(LOG_ERR, _("Error looking up `%s': %m"), c->hostname);
559       free_connection(c);
560       retry_outgoing(outgoing);
561       return;
562     }
563
564   c->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
565   c->hostname = hostlookup(htonl(c->address));
566
567   if(setup_outgoing_socket(c) < 0)
568     {
569       syslog(LOG_ERR, _("Could not set up a meta connection to %s (%s)"),
570              c->name, c->hostname);
571       retry_outgoing(outgoing);
572       return;
573     }
574
575   c->outgoing = outgoing;
576   c->last_ping_time = time(NULL);
577
578   connection_add(c);
579
580   send_id(c);
581 cp
582 }
583
584 int read_rsa_public_key(connection_t *c)
585 {
586   FILE *fp;
587   char *fname;
588   char *key;
589 cp
590   if(!c->rsa_key)
591     c->rsa_key = RSA_new();
592
593   /* First, check for simple PublicKey statement */
594
595   if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key))
596     {
597       BN_hex2bn(&c->rsa_key->n, key);
598       BN_hex2bn(&c->rsa_key->e, "FFFF");
599       return 0;
600     }
601
602   /* Else, check for PublicKeyFile statement and read it */
603
604   if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
605     {
606       if(is_safe_path(fname))
607         {
608           if((fp = fopen(fname, "r")) == NULL)
609             {
610               syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
611                      fname);
612               return -1;
613             }
614           c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
615           fclose(fp);
616           if(!c->rsa_key)
617             {
618               syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
619                      fname);
620               return -1;
621             }
622           return 0;
623         }
624       else
625         return -1;
626     }
627
628   /* Else, check if a harnessed public key is in the config file */
629
630   asprintf(&fname, "%s/hosts/%s", confbase, c->name);
631   if((fp = fopen(fname, "r")))
632     {
633       c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
634       fclose(fp);
635     }
636
637   free(fname);
638
639   if(c->rsa_key)
640     return 0;
641   else
642     {
643       syslog(LOG_ERR, _("No public key for %s specified!"), c->name);
644       return -1;
645     }
646 }
647
648 int read_rsa_private_key(void)
649 {
650   FILE *fp;
651   char *fname, *key;
652 cp
653   if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key))
654     {
655       myself->connection->rsa_key = RSA_new();
656       BN_hex2bn(&myself->connection->rsa_key->d, key);
657       BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
658     }
659   else if(get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
660     {
661       if((fp = fopen(fname, "r")) == NULL)
662         {
663           syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
664                  fname);
665           return -1;
666         }
667       myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
668       fclose(fp);
669       if(!myself->connection->rsa_key)
670         {
671           syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
672                  fname);
673           return -1;
674         }
675     }
676   else
677     {
678       syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
679       return -1;
680     }
681 cp
682   return 0;
683 }
684
685 /*
686   Configure node_t myself and set up the local sockets (listen only)
687 */
688 int setup_myself(void)
689 {
690   config_t *cfg;
691   subnet_t *subnet;
692   char *name, *mode, *cipher, *digest;
693   int choice;
694 cp
695   myself = new_node();
696   myself->connection = new_connection();
697   init_configuration(&myself->connection->config_tree);
698
699   asprintf(&myself->hostname, _("MYSELF"));
700   asprintf(&myself->connection->hostname, _("MYSELF"));
701
702   myself->connection->options = 0;
703   myself->connection->protocol_version = PROT_CURRENT;
704
705   if(!get_config_string(lookup_config(config_tree, "Name"), &name)) /* Not acceptable */
706     {
707       syslog(LOG_ERR, _("Name for tinc daemon required!"));
708       return -1;
709     }
710
711   if(check_id(name))
712     {
713       syslog(LOG_ERR, _("Invalid name for myself!"));
714       free(name);
715       return -1;
716     }
717
718   myself->name = name;
719   myself->connection->name = xstrdup(name);
720
721 cp
722   if(read_rsa_private_key())
723     return -1;
724
725   if(read_connection_config(myself->connection))
726     {
727       syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
728       return -1;
729     }
730
731   if(read_rsa_public_key(myself->connection))
732     return -1;
733 cp
734
735 /*
736   if(RSA_check_key(rsa_key) != 1)
737     {
738       syslog(LOG_ERR, _("Invalid public/private keypair!"));
739       return -1;
740     }
741 */
742   if(!get_config_port(lookup_config(myself->connection->config_tree, "Port"), &myself->port))
743     myself->port = 655;
744
745   myself->connection->port = myself->port;
746
747 /* Read in all the subnets specified in the host configuration file */
748
749   cfg = lookup_config(myself->connection->config_tree, "Subnet");
750
751   while(cfg)
752     {
753       if(!get_config_subnet(cfg, &subnet))
754         return -1;
755
756       subnet_add(myself, subnet);
757
758       cfg = lookup_config_next(myself->connection->config_tree, cfg);
759     }
760
761 cp
762   /* Check some options */
763
764   if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice))
765     if(choice)
766       myself->options |= OPTION_INDIRECT;
767
768   if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice))
769     if(choice)
770       myself->options |= OPTION_TCPONLY;
771
772   if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice))
773     if(choice)
774       myself->options |= OPTION_INDIRECT;
775
776   if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice))
777     if(choice)
778       myself->options |= OPTION_TCPONLY;
779
780   if(myself->options & OPTION_TCPONLY)
781     myself->options |= OPTION_INDIRECT;
782
783   if(get_config_string(lookup_config(config_tree, "Mode"), &mode))
784     {
785       if(!strcasecmp(mode, "router"))
786         routing_mode = RMODE_ROUTER;
787       else if (!strcasecmp(mode, "switch"))
788         routing_mode = RMODE_SWITCH;
789       else if (!strcasecmp(mode, "hub"))
790         routing_mode = RMODE_HUB;
791       else
792         {
793           syslog(LOG_ERR, _("Invalid routing mode!"));
794           return -1;
795         }
796     }
797   else
798     routing_mode = RMODE_ROUTER;
799
800 cp
801   /* Open sockets */
802   
803   if((tcp_socket = setup_listen_socket(myself->port)) < 0)
804     {
805       syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
806       return -1;
807     }
808
809   if((udp_socket = setup_vpn_in_socket(myself->port)) < 0)
810     {
811       syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
812       return -1;
813     }
814 cp
815   /* Generate packet encryption key */
816
817   if(get_config_string(lookup_config(myself->connection->config_tree, "Cipher"), &cipher))
818     {
819       if(!strcasecmp(cipher, "none"))
820         {
821           myself->cipher = NULL;
822         }
823       else
824         {
825           if(!(myself->cipher = EVP_get_cipherbyname(cipher)))
826             {
827               syslog(LOG_ERR, _("Unrecognized cipher type!"));
828               return -1;
829             }
830         }
831     }
832   else
833     myself->cipher = EVP_bf_cbc();
834
835   if(myself->cipher)
836     myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
837   else
838     myself->keylength = 1;
839
840   myself->key = (char *)xmalloc(myself->keylength);
841   RAND_pseudo_bytes(myself->key, myself->keylength);
842
843   if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
844     keylifetime = 3600;
845
846   keyexpires = time(NULL) + keylifetime;
847
848   /* Check if we want to use message authentication codes... */
849
850   if(get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest))
851     {
852       if(!strcasecmp(digest, "none"))
853         {
854           myself->digest = NULL;
855         }
856       else
857         {
858           if(!(myself->digest = EVP_get_digestbyname(digest)))
859             {
860               syslog(LOG_ERR, _("Unrecognized digest type!"));
861               return -1;
862             }
863         }
864     }
865   else
866     myself->digest = EVP_sha1();
867
868   if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->maclength))
869     {
870       if(myself->digest)
871         {
872           if(myself->maclength > myself->digest->md_size)
873             {
874               syslog(LOG_ERR, _("MAC length exceeds size of digest!"));
875               return -1;
876             }
877           else if (myself->maclength < 0)
878             {
879               syslog(LOG_ERR, _("Bogus MAC length!"));
880               return -1;
881             }
882         }
883     }
884   else
885     myself->maclength = 4;
886 cp
887   /* Done */
888
889   myself->nexthop = myself;
890   myself->via = myself;
891   myself->status.active = 1;
892   node_add(myself);
893
894   graph();
895
896   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
897 cp
898   return 0;
899 }
900
901 /*
902   setup all initial network connections
903 */
904 int setup_network_connections(void)
905 {
906 cp
907   init_connections();
908   init_subnets();
909   init_nodes();
910   init_edges();
911   init_events();
912
913   if(get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
914     {
915       if(pingtimeout < 1)
916         {
917           pingtimeout = 86400;
918         }
919     }
920   else
921     pingtimeout = 60;
922
923   if(setup_device() < 0)
924     return -1;
925
926   /* Run tinc-up script to further initialize the tap interface */
927   execute_script("tinc-up");
928
929   if(setup_myself() < 0)
930     return -1;
931
932   try_outgoing_connections();
933 cp
934   return 0;
935 }
936
937 /*
938   close all open network connections
939 */
940 void close_network_connections(void)
941 {
942   avl_node_t *node, *next;
943   connection_t *c;
944 cp
945   for(node = connection_tree->head; node; node = next)
946     {
947       next = node->next;
948       c = (connection_t *)node->data;
949       if(c->outgoing)
950         free(c->outgoing->name), free(c->outgoing);
951       terminate_connection(c, 0);
952     }
953
954   if(myself && myself->connection)
955     terminate_connection(myself->connection, 0);
956
957   close(udp_socket);
958   close(tcp_socket);
959
960   exit_events();
961   exit_edges();
962   exit_subnets();
963   exit_nodes();
964   exit_connections();
965
966   execute_script("tinc-down");
967
968   close_device();
969 cp
970   return;
971 }
972
973 /*
974   handle an incoming tcp connect call and open
975   a connection to it.
976 */
977 connection_t *create_new_connection(int sfd)
978 {
979   connection_t *c;
980   struct sockaddr_in ci;
981   int len = sizeof(ci);
982 cp
983   c = new_connection();
984
985   if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
986     {
987       syslog(LOG_ERR, _("System call `%s' failed: %m"),
988              "getpeername");
989       close(sfd);
990       return NULL;
991     }
992
993   c->address = ntohl(ci.sin_addr.s_addr);
994   c->hostname = hostlookup(ci.sin_addr.s_addr);
995   c->port = htons(ci.sin_port);
996   c->socket = sfd;
997   c->last_ping_time = time(NULL);
998
999   if(debug_lvl >= DEBUG_CONNECTIONS)
1000     syslog(LOG_NOTICE, _("Connection from %s port %d"),
1001          c->hostname, c->port);
1002
1003   c->allow_request = ID;
1004 cp
1005   return c;
1006 }
1007
1008 /*
1009   put all file descriptors in an fd_set array
1010 */
1011 void build_fdset(fd_set *fs)
1012 {
1013   avl_node_t *node;
1014   connection_t *c;
1015 cp
1016   FD_ZERO(fs);
1017
1018   for(node = connection_tree->head; node; node = node->next)
1019     {
1020       c = (connection_t *)node->data;
1021       FD_SET(c->socket, fs);
1022     }
1023
1024   FD_SET(tcp_socket, fs);
1025   FD_SET(udp_socket, fs);
1026   FD_SET(device_fd, fs);
1027 cp
1028 }
1029
1030 /*
1031   receive incoming data from the listening
1032   udp socket and write it to the ethertap
1033   device after being decrypted
1034 */
1035 void handle_incoming_vpn_data(void)
1036 {
1037   vpn_packet_t pkt;
1038   int x, l = sizeof(x);
1039   struct sockaddr_in from;
1040   socklen_t fromlen = sizeof(from);
1041   node_t *n;
1042 cp
1043   if(getsockopt(udp_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1044     {
1045       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1046              __FILE__, __LINE__, udp_socket);
1047       return;
1048     }
1049   if(x)
1050     {
1051       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1052       return;
1053     }
1054
1055   if((pkt.len = recvfrom(udp_socket, (char *)&pkt.seqno, MAXSIZE, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1056     {
1057       syslog(LOG_ERR, _("Receiving packet failed: %m"));
1058       return;
1059     }
1060
1061   n = lookup_node_udp(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1062
1063   if(!n)
1064     {
1065       syslog(LOG_WARNING, _("Received UDP packet on port %hd from unknown source %x:%hd"), myself->port, ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1066       return;
1067     }
1068
1069 /*
1070   if(n->connection)
1071     n->connection->last_ping_time = time(NULL);
1072 */
1073   receive_udppacket(n, &pkt);
1074 cp
1075 }
1076
1077 /* Purge edges and subnets of unreachable nodes. Use carefully. */
1078
1079 void purge(void)
1080 {
1081   avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext, *cnode;
1082   node_t *n;
1083   edge_t *e;
1084   subnet_t *s;
1085   connection_t *c;
1086 cp
1087   if(debug_lvl >= DEBUG_PROTOCOL)
1088     syslog(LOG_DEBUG, _("Purging unreachable nodes"));
1089
1090   for(nnode = node_tree->head; nnode; nnode = nnext)
1091   {
1092     nnext = nnode->next;
1093     n = (node_t *)nnode->data;
1094
1095     if(!n->status.reachable)
1096     {
1097       if(debug_lvl >= DEBUG_SCARY_THINGS)
1098         syslog(LOG_DEBUG, _("Purging node %s (%s)"), n->name, n->hostname);
1099
1100       for(snode = n->subnet_tree->head; snode; snode = snext)
1101       {
1102         snext = snode->next;
1103         s = (subnet_t *)snode->data;
1104         
1105         for(cnode = connection_tree->head; cnode; cnode = cnode->next)
1106         {
1107           c = (connection_t *)cnode->data;
1108           if(c->status.active)
1109             send_del_subnet(c, s);
1110         }
1111         
1112         subnet_del(n, s);
1113       }
1114         
1115       for(enode = n->edge_tree->head; enode; enode = enext)
1116       {
1117         enext = enode->next;
1118         e = (edge_t *)enode->data;
1119         
1120         for(cnode = connection_tree->head; cnode; cnode = cnode->next)
1121         {
1122           c = (connection_t *)cnode->data;
1123           if(c->status.active)
1124             send_del_edge(c, e);
1125         }
1126         
1127         edge_del(e);
1128       }
1129
1130       node_del(n);
1131     }
1132   }     
1133 cp
1134 }
1135
1136 /*
1137   Terminate a connection:
1138   - Close the socket
1139   - Remove associated edge and tell other connections about it if report = 1
1140   - Check if we need to retry making an outgoing connection
1141   - Deactivate the host
1142 */
1143 void terminate_connection(connection_t *c, int report)
1144 {
1145   avl_node_t *node;
1146   connection_t *other;
1147 cp
1148   if(c->status.remove)
1149     return;
1150   
1151   if(debug_lvl >= DEBUG_CONNECTIONS)
1152     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1153            c->name, c->hostname);
1154
1155   c->status.remove = 1;
1156   
1157   if(c->socket)
1158     close(c->socket);
1159
1160   if(c->edge)
1161     {
1162       if(report)
1163         {
1164           for(node = connection_tree->head; node; node = node->next)
1165             {
1166               other = (connection_t *)node->data;
1167               if(other->status.active && other != c)
1168                 send_del_edge(other, c->edge);
1169             }
1170         }
1171
1172       edge_del(c->edge);
1173     }
1174
1175   /* Run MST and SSSP algorithms */
1176   
1177   graph();
1178
1179   /* Check if this was our outgoing connection */
1180
1181   if(c->outgoing)
1182     {
1183       retry_outgoing(c->outgoing);
1184       c->outgoing = NULL;
1185     }
1186
1187   /* Deactivate */
1188
1189   c->status.active = 0;
1190   if(c->node)
1191     c->node->connection = NULL;
1192   do_prune = 1;
1193 cp
1194 }
1195
1196 /*
1197   Check if the other end is active.
1198   If we have sent packets, but didn't receive any,
1199   then possibly the other end is dead. We send a
1200   PING request over the meta connection. If the other
1201   end does not reply in time, we consider them dead
1202   and close the connection.
1203 */
1204 void check_dead_connections(void)
1205 {
1206   time_t now;
1207   avl_node_t *node, *next;
1208   connection_t *c;
1209 cp
1210   now = time(NULL);
1211
1212   for(node = connection_tree->head; node; node = next)
1213     {
1214       next = node->next;
1215       c = (connection_t *)node->data;
1216       if(c->last_ping_time + pingtimeout < now)
1217         {
1218           if(c->status.active)
1219             {
1220               if(c->status.pinged)
1221                 {
1222                   if(debug_lvl >= DEBUG_PROTOCOL)
1223                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1224                            c->name, c->hostname);
1225                   c->status.timeout = 1;
1226                   terminate_connection(c, 1);
1227                 }
1228               else
1229                 {
1230                   send_ping(c);
1231                 }
1232             }
1233           else
1234             {
1235               if(debug_lvl >= DEBUG_CONNECTIONS)
1236                 syslog(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
1237                        c->name, c->hostname);
1238               terminate_connection(c, 0);
1239             }
1240         }
1241     }
1242 cp
1243 }
1244
1245 /*
1246   accept a new tcp connect and create a
1247   new connection
1248 */
1249 int handle_new_meta_connection()
1250 {
1251   connection_t *new;
1252   struct sockaddr client;
1253   int fd, len = sizeof(client);
1254 cp
1255   if((fd = accept(tcp_socket, &client, &len)) < 0)
1256     {
1257       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1258       return -1;
1259     }
1260
1261   if(!(new = create_new_connection(fd)))
1262     {
1263       shutdown(fd, 2);
1264       close(fd);
1265       syslog(LOG_NOTICE, _("Closed attempted connection"));
1266       return 0;
1267     }
1268
1269   connection_add(new);
1270
1271   send_id(new);
1272 cp
1273   return 0;
1274 }
1275
1276 void try_outgoing_connections(void)
1277 {
1278   static config_t *cfg = NULL;
1279   char *name;
1280   outgoing_t *outgoing;
1281 cp
1282   for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg))
1283     {
1284       get_config_string(cfg, &name);
1285
1286       if(check_id(name))
1287         {
1288           syslog(LOG_ERR, _("Invalid name for outgoing connection in %s line %d"), cfg->file, cfg->line);
1289           free(name);
1290           continue;
1291         }
1292
1293       outgoing = xmalloc_and_zero(sizeof(*outgoing));
1294       outgoing->name = name;
1295       setup_outgoing_connection(outgoing);
1296     }
1297 }
1298
1299 /*
1300   check all connections to see if anything
1301   happened on their sockets
1302 */
1303 void check_network_activity(fd_set *f)
1304 {
1305   connection_t *c;
1306   avl_node_t *node;
1307 cp
1308   if(FD_ISSET(udp_socket, f))
1309     handle_incoming_vpn_data();
1310
1311   for(node = connection_tree->head; node; node = node->next)
1312     {
1313       c = (connection_t *)node->data;
1314
1315       if(c->status.remove)
1316         return;
1317
1318       if(FD_ISSET(c->socket, f))
1319         if(receive_meta(c) < 0)
1320           {
1321             terminate_connection(c, c->status.active);
1322             return;
1323           }
1324     }
1325
1326   if(FD_ISSET(tcp_socket, f))
1327     handle_new_meta_connection();
1328 cp
1329 }
1330
1331 void prune_connections(void)
1332 {
1333   connection_t *c;
1334   avl_node_t *node, *next;
1335 cp
1336   for(node = connection_tree->head; node; node = next)
1337     {
1338       next = node->next;
1339       c = (connection_t *)node->data;
1340
1341       if(c->status.remove)
1342         connection_del(c);
1343     }
1344   
1345   if(!connection_tree->head)
1346     purge();
1347 cp
1348 }
1349
1350 /*
1351   this is where it all happens...
1352 */
1353 void main_loop(void)
1354 {
1355   fd_set fset;
1356   struct timeval tv;
1357   int r;
1358   time_t last_ping_check;
1359   int t;
1360   event_t *event;
1361   vpn_packet_t packet;
1362 cp
1363   last_ping_check = time(NULL);
1364
1365   srand(time(NULL));
1366
1367   for(;;)
1368     {
1369       tv.tv_sec = 1 + (rand() & 7); /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
1370       tv.tv_usec = 0;
1371
1372       if(do_prune)
1373         {
1374           prune_connections();
1375           do_prune = 0;
1376         }
1377
1378       build_fdset(&fset);
1379
1380       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1381         {
1382           if(errno != EINTR) /* because of a signal */
1383             {
1384               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1385               return;
1386             }
1387         }
1388
1389       if(sighup)
1390         {
1391           syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1392           sighup = 0;
1393           close_network_connections();
1394           exit_configuration(&config_tree);
1395
1396           if(read_server_config())
1397             {
1398               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1399               exit(1);
1400             }
1401
1402           sleep(5);
1403
1404           if(setup_network_connections())
1405             return;
1406
1407           continue;
1408         }
1409
1410       if(do_purge)
1411         {
1412           purge();
1413           do_purge = 0;
1414         }
1415
1416       t = time(NULL);
1417
1418       /* Let's check if everybody is still alive */
1419
1420       if(last_ping_check + pingtimeout < t)
1421         {
1422           check_dead_connections();
1423           last_ping_check = time(NULL);
1424
1425           /* Should we regenerate our key? */
1426
1427           if(keyexpires < t)
1428             {
1429               if(debug_lvl >= DEBUG_STATUS)
1430                 syslog(LOG_INFO, _("Regenerating symmetric key"));
1431
1432               RAND_pseudo_bytes(myself->key, myself->keylength);
1433               send_key_changed(myself->connection, myself);
1434               keyexpires = time(NULL) + keylifetime;
1435             }
1436         }
1437
1438       if(sigalrm)
1439         {
1440           syslog(LOG_INFO, _("Flushing event queue"));
1441
1442           while(event_tree->head)
1443             {
1444               event = (event_t *)event_tree->head->data;
1445               event->handler(event->data);
1446               event_del(event);
1447             }
1448           sigalrm = 0;
1449         }
1450
1451       while((event = get_expired_event()))
1452         {
1453           event->handler(event->data);
1454           free(event);
1455         }
1456
1457       if(r > 0)
1458         {
1459           check_network_activity(&fset);
1460
1461           /* local tap data */
1462           if(FD_ISSET(device_fd, &fset))
1463             {
1464               if(!read_packet(&packet))
1465                 route_outgoing(&packet);
1466             }
1467         }
1468     }
1469 cp
1470 }