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