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