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