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