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