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