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