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