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