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