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