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