308a64f6796007685878338c92bab2e9d52063ff
[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.57 2000/11/02 22:05:35 zarq Exp $
21 */
22
23 #include "config.h"
24
25 #include <arpa/inet.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <linux/sockios.h>
29 #include <net/if.h>
30 #include <netdb.h>
31 #include <netinet/in.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <sys/signal.h>
36 #include <sys/socket.h>
37 #include <sys/time.h>
38 #include <sys/types.h>
39 #include <syslog.h>
40 #include <unistd.h>
41 #include <sys/ioctl.h>
42 #include <openssl/rand.h>
43 #include <openssl/evp.h>
44 #include <openssl/err.h>
45
46 #ifdef HAVE_TUNTAP
47 #include LINUX_IF_TUN_H
48 #endif
49
50 #include <utils.h>
51 #include <xalloc.h>
52
53 #include "conf.h"
54 #include "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, _("System call `%s' failed: %m"),
461              "setsockopt");
462       return -1;
463     }
464
465   if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
466     {
467       syslog(LOG_ERR, _("System call `%s' failed: %m"),
468              "setsockopt");
469       return -1;
470     }
471
472   flags = fcntl(nfd, F_GETFL);
473   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
474     {
475       syslog(LOG_ERR, _("System call `%s' failed: %m"),
476              "fcntl");
477       return -1;
478     }
479
480   if((cfg = get_config_val(config, interface)))
481     {
482       if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
483         {
484           syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
485           return -1;
486         }
487     }
488
489   memset(&a, 0, sizeof(a));
490   a.sin_family = AF_INET;
491   a.sin_port = htons(port);
492   
493   if((cfg = get_config_val(config, interfaceip)))
494     a.sin_addr.s_addr = htonl(cfg->data.ip->address);
495   else
496     a.sin_addr.s_addr = htonl(INADDR_ANY);
497
498   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
499     {
500       syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
501       return -1;
502     }
503
504   if(listen(nfd, 3))
505     {
506       syslog(LOG_ERR, _("System call `%s' failed: %m"),
507              "listen");
508       return -1;
509     }
510 cp
511   return nfd;
512 }
513
514 /*
515   setup the socket for incoming encrypted
516   data (the udp part)
517 */
518 int setup_vpn_in_socket(int port)
519 {
520   int nfd, flags;
521   struct sockaddr_in a;
522   const int one = 1;
523 cp
524   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
525     {
526       syslog(LOG_ERR, _("Creating socket failed: %m"));
527       return -1;
528     }
529
530   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
531     {
532       syslog(LOG_ERR, _("System call `%s' failed: %m"),
533              "setsockopt");
534       return -1;
535     }
536
537   flags = fcntl(nfd, F_GETFL);
538   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
539     {
540       syslog(LOG_ERR, _("System call `%s' failed: %m"),
541              "fcntl");
542       return -1;
543     }
544
545   memset(&a, 0, sizeof(a));
546   a.sin_family = AF_INET;
547   a.sin_port = htons(port);
548   a.sin_addr.s_addr = htonl(INADDR_ANY);
549
550   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
551     {
552       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
553       return -1;
554     }
555 cp
556   return nfd;
557 }
558
559 /*
560   setup an outgoing meta (tcp) socket
561 */
562 int setup_outgoing_meta_socket(conn_list_t *cl)
563 {
564   int flags;
565   struct sockaddr_in a;
566   config_t const *cfg;
567 cp
568   if(debug_lvl >= DEBUG_CONNECTIONS)
569     syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
570
571   if((cfg = get_config_val(cl->config, port)) == NULL)
572     cl->port = 655;
573   else
574     cl->port = cfg->data.val;
575
576   cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
577   if(cl->meta_socket == -1)
578     {
579       syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
580              cl->hostname, cl->port);
581       return -1;
582     }
583
584   a.sin_family = AF_INET;
585   a.sin_port = htons(cl->port);
586   a.sin_addr.s_addr = htonl(cl->address);
587
588   if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
589     {
590       syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
591       return -1;
592     }
593
594   flags = fcntl(cl->meta_socket, F_GETFL);
595   if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
596     {
597       syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
598              cl->hostname, cl->port);
599       return -1;
600     }
601
602   if(debug_lvl >= DEBUG_CONNECTIONS)
603     syslog(LOG_INFO, _("Connected to %s port %hd"),
604          cl->hostname, cl->port);
605
606   cl->status.meta = 1;
607 cp
608   return 0;
609 }
610
611 /*
612   setup an outgoing connection. It's not
613   necessary to also open an udp socket as
614   well, because the other host will initiate
615   an authentication sequence during which
616   we will do just that.
617 */
618 int setup_outgoing_connection(char *name)
619 {
620   conn_list_t *ncn;
621   struct hostent *h;
622   config_t *cfg;
623 cp
624   if(check_id(name))
625     {
626       syslog(LOG_ERR, _("Invalid name for outgoing connection"));
627       return -1;
628     }
629
630   ncn = new_conn_list();
631   asprintf(&ncn->name, "%s", name);
632     
633   if(read_host_config(ncn))
634     {
635       syslog(LOG_ERR, _("Error reading host configuration file for %s"));
636       free_conn_list(ncn);
637       return -1;
638     }
639     
640   if(!(cfg = get_config_val(ncn->config, address)))
641     {
642       syslog(LOG_ERR, _("No address specified for %s"));
643       free_conn_list(ncn);
644       return -1;
645     }
646     
647   if(!(h = gethostbyname(cfg->data.ptr)))
648     {
649       syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
650       free_conn_list(ncn);
651       return -1;
652     }
653
654   ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
655   ncn->hostname = hostlookup(htonl(ncn->address));
656   
657   if(setup_outgoing_meta_socket(ncn) < 0)
658     {
659       syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
660              ncn->hostname);
661       free_conn_list(ncn);
662       return -1;
663     }
664
665   ncn->status.outgoing = 1;
666   ncn->buffer = xmalloc(MAXBUFSIZE);
667   ncn->buflen = 0;
668   ncn->last_ping_time = time(NULL);
669   ncn->want_ping = 0;
670
671   conn_list_add(ncn);
672
673   send_id(ncn);
674 cp
675   return 0;
676 }
677
678 /*
679   Configure conn_list_t myself and set up the local sockets (listen only)
680 */
681 int setup_myself(void)
682 {
683   config_t const *cfg;
684   subnet_t *net;
685 cp
686   myself = new_conn_list();
687
688   asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
689   myself->flags = 0;
690   myself->protocol_version = PROT_CURRENT;
691
692   if(!(cfg = get_config_val(config, tincname))) /* Not acceptable */
693     {
694       syslog(LOG_ERR, _("Name for tinc daemon required!"));
695       return -1;
696     }
697   else
698     asprintf(&myself->name, "%s", (char*)cfg->data.val);
699
700   if(check_id(myself->name))
701     {
702       syslog(LOG_ERR, _("Invalid name for myself!"));
703       return -1;
704     }
705 cp
706   if(!(cfg = get_config_val(config, privatekey)))
707     {
708       syslog(LOG_ERR, _("Private key for tinc daemon required!"));
709       return -1;
710     }
711   else
712     {
713       myself->rsa_key = RSA_new();
714       BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
715       BN_hex2bn(&myself->rsa_key->e, "FFFF");
716     }
717
718   if(read_host_config(myself))
719     {
720       syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
721       return -1;
722     }
723 cp  
724   if(!(cfg = get_config_val(myself->config, publickey)))
725     {
726       syslog(LOG_ERR, _("Public key for tinc daemon required!"));
727       return -1;
728     }
729   else
730     {
731       BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
732     }
733 /*
734   if(RSA_check_key(myself->rsa_key) != 1)
735     {
736       syslog(LOG_ERR, _("Invalid public/private keypair!"));
737       return -1;
738     }
739 */
740   if(!(cfg = get_config_val(myself->config, port)))
741     myself->port = 655;
742   else
743     myself->port = cfg->data.val;
744
745   if((cfg = get_config_val(myself->config, indirectdata)))
746     if(cfg->data.val == stupid_true)
747       myself->flags |= EXPORTINDIRECTDATA;
748
749   if((cfg = get_config_val(myself->config, tcponly)))
750     if(cfg->data.val == stupid_true)
751       myself->flags |= TCPONLY;
752
753 /* Read in all the subnets specified in the host configuration file */
754
755   for(cfg = myself->config; (cfg = get_config_val(cfg, subnet)); cfg = cfg->next)
756     {
757       net = new_subnet();
758       net->type = SUBNET_IPV4;
759       net->net.ipv4.address = cfg->data.ip->address;
760       net->net.ipv4.mask = cfg->data.ip->mask;
761       
762       /* Teach newbies what subnets are... */
763       
764       if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
765         {
766           syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
767           return -1;
768         }        
769       
770       subnet_add(myself, net);
771     }
772     
773   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
774     {
775       syslog(LOG_ERR, _("Unable to set up a listening socket!"));
776       return -1;
777     }
778
779   if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
780     {
781       syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket!"));
782       close(myself->meta_socket);
783       return -1;
784     }
785
786   /* Generate packet encryption key */
787
788   myself->cipher_pkttype = EVP_bf_cfb();
789
790   myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
791
792   myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
793   RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
794
795   if(!(cfg = get_config_val(config, keyexpire)))
796     keylifetime = 3600;
797   else
798     keylifetime = cfg->data.val;
799     
800   keyexpires = time(NULL) + keylifetime;
801
802   /* Activate ourselves */
803   
804   myself->status.active = 1;
805
806   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
807 cp
808   return 0;
809 }
810
811 RETSIGTYPE
812 sigalrm_handler(int a)
813 {
814   config_t const *cfg;
815 cp
816   cfg = get_config_val(upstreamcfg, connectto);
817
818   if(!cfg && upstreamcfg == config)
819     /* No upstream IP given, we're listen only. */
820     return;
821
822   while(cfg)
823     {
824       upstreamcfg = cfg->next;
825       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
826         {
827           signal(SIGALRM, SIG_IGN);
828           return;
829         }
830       cfg = get_config_val(upstreamcfg, connectto); /* Or else we try the next ConnectTo line */
831     }
832
833   signal(SIGALRM, sigalrm_handler);
834   upstreamcfg = config;
835   seconds_till_retry += 5;
836   if(seconds_till_retry > MAXTIMEOUT)    /* Don't wait more than MAXTIMEOUT seconds. */
837     seconds_till_retry = MAXTIMEOUT;
838   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
839          seconds_till_retry);
840   alarm(seconds_till_retry);
841 cp
842 }
843
844 /*
845   setup all initial network connections
846 */
847 int setup_network_connections(void)
848 {
849   config_t const *cfg;
850   char *scriptname;
851 cp
852   if((cfg = get_config_val(config, pingtimeout)) == NULL)
853     timeout = 5;
854   else
855     timeout = cfg->data.val;
856
857   if(setup_tap_fd() < 0)
858     return -1;
859
860   if(setup_myself() < 0)
861     return -1;
862
863   /* Run tinc-up script to further initialize the tap interface */
864
865   asprintf(&scriptname, "%s/tinc-up", confbase);
866
867   if(!fork())
868     {
869       execl(scriptname, NULL);
870
871       if(errno != ENOENT)
872         syslog(LOG_WARNING, _("Error while executing %s: %m"), scriptname);
873
874       exit(0);
875     }
876
877   free(scriptname);
878
879   if(!(cfg = get_config_val(config, connectto)))
880     /* No upstream IP given, we're listen only. */
881     return 0;
882
883   while(cfg)
884     {
885       upstreamcfg = cfg->next;
886       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
887         return 0;
888       cfg = get_config_val(upstreamcfg, connectto); /* Or else we try the next ConnectTo line */
889     }
890     
891   signal(SIGALRM, sigalrm_handler);
892   upstreamcfg = config;
893   seconds_till_retry = MAXTIMEOUT;
894   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
895   alarm(seconds_till_retry);
896 cp
897   return 0;
898 }
899
900 /*
901   close all open network connections
902 */
903 void close_network_connections(void)
904 {
905   conn_list_t *p;
906   char *scriptname;
907 cp
908   for(p = conn_list; p != NULL; p = p->next)
909     {
910       p->status.active = 0;
911       terminate_connection(p);
912     }
913
914   if(myself)
915     if(myself->status.active)
916       {
917         close(myself->meta_socket);
918         close(myself->socket);
919         free_conn_list(myself);
920         myself = NULL;
921       }
922
923   /* Execute tinc-down script right before shutting down the interface */
924
925   asprintf(&scriptname, "%s/tinc-down", confbase);
926
927   if(!fork())
928     {
929       execl(scriptname, NULL);
930
931       if(errno != ENOENT)
932         syslog(LOG_WARNING, _("Error while executing %s: %m"), scriptname);
933
934       exit(0);
935     }
936       
937   free(scriptname);
938
939   close(tap_fd);
940   destroy_conn_list();
941
942   syslog(LOG_NOTICE, _("Terminating"));
943 cp
944   return;
945 }
946
947 /*
948   create a data (udp) socket
949 */
950 int setup_vpn_connection(conn_list_t *cl)
951 {
952   int nfd, flags;
953   struct sockaddr_in a;
954 cp
955   if(debug_lvl >= DEBUG_TRAFFIC)
956     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
957
958   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
959   if(nfd == -1)
960     {
961       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
962       return -1;
963     }
964
965   a.sin_family = AF_INET;
966   a.sin_port = htons(cl->port);
967   a.sin_addr.s_addr = htonl(cl->address);
968
969   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
970     {
971       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
972              cl->hostname, cl->port);
973       return -1;
974     }
975
976   flags = fcntl(nfd, F_GETFL);
977   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
978     {
979       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
980              cl->name, cl->hostname);
981       return -1;
982     }
983
984   cl->socket = nfd;
985   cl->status.dataopen = 1;
986 cp
987   return 0;
988 }
989
990 /*
991   handle an incoming tcp connect call and open
992   a connection to it.
993 */
994 conn_list_t *create_new_connection(int sfd)
995 {
996   conn_list_t *p;
997   struct sockaddr_in ci;
998   int len = sizeof(ci);
999 cp
1000   p = new_conn_list();
1001
1002   if(getpeername(sfd, &ci, &len) < 0)
1003     {
1004       syslog(LOG_ERR, _("System call `%s' failed: %m"),
1005              "getpeername");
1006       return NULL;
1007     }
1008
1009   p->name = unknown;
1010   p->address = ntohl(ci.sin_addr.s_addr);
1011   p->hostname = hostlookup(ci.sin_addr.s_addr);
1012   p->meta_socket = sfd;
1013   p->status.meta = 1;
1014   p->buffer = xmalloc(MAXBUFSIZE);
1015   p->buflen = 0;
1016   p->last_ping_time = time(NULL);
1017   p->want_ping = 0;
1018   
1019   if(debug_lvl >= DEBUG_CONNECTIONS)
1020     syslog(LOG_NOTICE, _("Connection from %s port %d"),
1021          p->hostname, htons(ci.sin_port));
1022
1023   p->allow_request = ID;
1024 cp
1025   return p;
1026 }
1027
1028 /*
1029   put all file descriptors in an fd_set array
1030 */
1031 void build_fdset(fd_set *fs)
1032 {
1033   conn_list_t *p;
1034 cp
1035   FD_ZERO(fs);
1036
1037   for(p = conn_list; p != NULL; p = p->next)
1038     {
1039       if(p->status.meta)
1040         FD_SET(p->meta_socket, fs);
1041       if(p->status.dataopen)
1042         FD_SET(p->socket, fs);
1043     }
1044
1045   FD_SET(myself->meta_socket, fs);
1046   FD_SET(myself->socket, fs);
1047   FD_SET(tap_fd, fs);
1048 cp
1049 }
1050
1051 /*
1052   receive incoming data from the listening
1053   udp socket and write it to the ethertap
1054   device after being decrypted
1055 */
1056 int handle_incoming_vpn_data()
1057 {
1058   vpn_packet_t pkt;
1059   int x, l = sizeof(x);
1060   struct sockaddr from;
1061   int lenin;
1062   socklen_t fromlen = sizeof(from);
1063 cp
1064   if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1065     {
1066       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1067              __FILE__, __LINE__, myself->socket);
1068       return -1;
1069     }
1070   if(x)
1071     {
1072       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1073       return -1;
1074     }
1075
1076   if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, &from, &fromlen)) <= 0)
1077     {
1078       syslog(LOG_ERR, _("Receiving packet failed: %m"));
1079       return -1;
1080     }
1081
1082   if(debug_lvl >= DEBUG_TRAFFIC)
1083     {
1084       syslog(LOG_DEBUG, _("Received packet of %d bytes"), lenin);
1085     } 
1086
1087 cp
1088   return xrecv(&pkt);
1089 }
1090
1091 /*
1092   terminate a connection and notify the other
1093   end before closing the sockets
1094 */
1095 void terminate_connection(conn_list_t *cl)
1096 {
1097   conn_list_t *p;
1098   subnet_t *s;
1099 cp
1100   if(cl->status.remove)
1101     return;
1102
1103   cl->status.remove = 1;
1104
1105   if(debug_lvl >= DEBUG_CONNECTIONS)
1106     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1107            cl->name, cl->hostname);
1108  
1109   if(cl->socket)
1110     close(cl->socket);
1111   if(cl->status.meta)
1112     close(cl->meta_socket);
1113
1114 cp
1115   /* Find all connections that were lost because they were behind cl
1116      (the connection that was dropped). */
1117
1118   if(cl->status.meta)
1119     for(p = conn_list; p != NULL; p = p->next)
1120       if((p->nexthop == cl) && (p != cl))
1121         terminate_connection(p);        /* Sounds like recursion, but p does not have a meta connection :) */
1122
1123   /* Inform others of termination if it was still active */
1124
1125   if(cl->status.active)
1126     for(p = conn_list; p != NULL; p = p->next)
1127       if(p->status.meta && p->status.active && p!=cl)
1128         send_del_host(p, cl);
1129
1130   /* Remove the associated subnets */
1131
1132   for(s = cl->subnets; s; s = s->next)
1133     subnet_del(s);
1134
1135   /* Check if this was our outgoing connection */
1136     
1137   if(cl->status.outgoing && cl->status.active)
1138     {
1139       signal(SIGALRM, sigalrm_handler);
1140       seconds_till_retry = 5;
1141       alarm(seconds_till_retry);
1142       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1143     }
1144
1145   /* Inactivate */
1146
1147   cl->status.active = 0;
1148 cp
1149 }
1150
1151 /*
1152   Check if the other end is active.
1153   If we have sent packets, but didn't receive any,
1154   then possibly the other end is dead. We send a
1155   PING request over the meta connection. If the other
1156   end does not reply in time, we consider them dead
1157   and close the connection.
1158 */
1159 int check_dead_connections(void)
1160 {
1161   conn_list_t *p;
1162   time_t now;
1163 cp
1164   now = time(NULL);
1165   for(p = conn_list; p != NULL; p = p->next)
1166     {
1167       if(p->status.active && p->status.meta)
1168         {
1169           if(p->last_ping_time + timeout < now)
1170             {
1171               if(p->status.pinged && !p->status.got_pong)
1172                 {
1173                   if(debug_lvl >= DEBUG_PROTOCOL)
1174                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1175                            p->name, p->hostname);
1176                   p->status.timeout = 1;
1177                   terminate_connection(p);
1178                 }
1179               else if(p->want_ping)
1180                 {
1181                   send_ping(p);
1182                   p->last_ping_time = now;
1183                   p->status.pinged = 1;
1184                   p->status.got_pong = 0;
1185                 }
1186             }
1187         }
1188     }
1189 cp
1190   return 0;
1191 }
1192
1193 /*
1194   accept a new tcp connect and create a
1195   new connection
1196 */
1197 int handle_new_meta_connection()
1198 {
1199   conn_list_t *ncn;
1200   struct sockaddr client;
1201   int nfd, len = sizeof(client);
1202 cp
1203   if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1204     {
1205       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1206       return -1;
1207     }
1208
1209   if(!(ncn = create_new_connection(nfd)))
1210     {
1211       shutdown(nfd, 2);
1212       close(nfd);
1213       syslog(LOG_NOTICE, _("Closed attempted connection"));
1214       return 0;
1215     }
1216
1217   conn_list_add(ncn);
1218 cp
1219   return 0;
1220 }
1221
1222 /*
1223   check all connections to see if anything
1224   happened on their sockets
1225 */
1226 void check_network_activity(fd_set *f)
1227 {
1228   conn_list_t *p;
1229   int x, l = sizeof(x);
1230 cp
1231   for(p = conn_list; p != NULL; p = p->next)
1232     {
1233       if(p->status.remove)
1234         continue;
1235
1236       if(p->status.dataopen)
1237         if(FD_ISSET(p->socket, f))
1238           {
1239             /*
1240               The only thing that can happen to get us here is apparently an
1241               error on this outgoing(!) UDP socket that isn't immediate (i.e.
1242               something that will not trigger an error directly on send()).
1243               I've once got here when it said `No route to host'.
1244             */
1245             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1246             syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1247                    p->name, p->hostname, strerror(x));
1248             terminate_connection(p);
1249             return;
1250           }  
1251
1252       if(p->status.meta)
1253         if(FD_ISSET(p->meta_socket, f))
1254           if(receive_meta(p) < 0)
1255             {
1256               terminate_connection(p);
1257               return;
1258             } 
1259     }
1260   
1261   if(FD_ISSET(myself->socket, f))
1262     handle_incoming_vpn_data();
1263
1264   if(FD_ISSET(myself->meta_socket, f))
1265     handle_new_meta_connection();
1266 cp
1267 }
1268
1269 /*
1270   read, encrypt and send data that is
1271   available through the ethertap device
1272 */
1273 void handle_tap_input(void)
1274 {
1275   vpn_packet_t vp;
1276   int lenin;
1277 cp  
1278   if(taptype == TAP_TYPE_TUNTAP)
1279     {
1280       if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1281         {
1282           syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1283           return;
1284         }
1285       vp.len = lenin;
1286     }
1287   else                  /* ethertap */
1288     {
1289       if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1290         {
1291           syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1292           return;
1293         }
1294       vp.len = lenin - 2;
1295     }
1296
1297   total_tap_in += lenin;
1298
1299   if(lenin < 32)
1300     {
1301       if(debug_lvl >= DEBUG_TRAFFIC)
1302         syslog(LOG_WARNING, _("Received short packet from tap device"));
1303       return;
1304     }
1305
1306   if(debug_lvl >= DEBUG_TRAFFIC)
1307     {
1308       syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1309     }
1310
1311   send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1312 cp
1313 }
1314
1315 /*
1316   this is where it all happens...
1317 */
1318 void main_loop(void)
1319 {
1320   fd_set fset;
1321   struct timeval tv;
1322   int r;
1323   time_t last_ping_check;
1324   int t;
1325 cp
1326   last_ping_check = time(NULL);
1327
1328   for(;;)
1329     {
1330       tv.tv_sec = timeout;
1331       tv.tv_usec = 0;
1332
1333       prune_conn_list();
1334       build_fdset(&fset);
1335
1336       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1337         {
1338           if(errno != EINTR) /* because of alarm */
1339             {
1340               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1341               return;
1342             }
1343         }
1344
1345       if(sighup)
1346         {
1347           syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1348           sighup = 0;
1349           close_network_connections();
1350           clear_config(&config);
1351
1352           if(read_server_config())
1353             {
1354               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1355               exit(0);
1356             }
1357
1358           sleep(5);
1359           
1360           if(setup_network_connections())
1361             return;
1362             
1363           continue;
1364         }
1365
1366       t = time(NULL);
1367
1368       /* Let's check if everybody is still alive */
1369
1370       if(last_ping_check + timeout < t)
1371         {
1372           check_dead_connections();
1373           last_ping_check = time(NULL);
1374
1375           /* Should we regenerate our key? */
1376
1377           if(keyexpires < t)
1378             {
1379               if(debug_lvl >= DEBUG_STATUS)
1380                 syslog(LOG_INFO, _("Regenerating symmetric key"));
1381                 
1382               RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1383               send_key_changed(myself, NULL);
1384               keyexpires = time(NULL) + keylifetime;
1385             }
1386         }
1387
1388       if(r > 0)
1389         {
1390           check_network_activity(&fset);
1391
1392           /* local tap data */
1393           if(FD_ISSET(tap_fd, &fset))
1394             handle_tap_input();
1395         }
1396     }
1397 cp
1398 }