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