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