Include linux/sockios.h and net/if.h anyway, regardless of the value of HAVE_TUNTAP.
[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.44 2000/10/22 13:37:15 zarq Exp $
21 */
22
23 #include "config.h"
24
25 #include <arpa/inet.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <linux/sockios.h>
29 #include <net/if.h>
30 #include <netdb.h>
31 #include <netinet/in.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <sys/signal.h>
36 #include <sys/socket.h>
37 #include <sys/time.h>
38 #include <sys/types.h>
39 #include <syslog.h>
40 #include <unistd.h>
41
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 int upstreamindex = 0;
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   if(debug_lvl > DEBUG_TRAFFIC)
131     syslog(LOG_ERR, _("Receiving packet of %d bytes"),
132            inpkt->len);
133
134   outpkt.len = inpkt->len;
135   EVP_DecryptInit(myself->cipher_pktctx, myself->cipher_pkttype, myself->cipher_pktkey, NULL);
136   EVP_DecryptUpdate(myself->cipher_pktctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
137   /* FIXME: grok DecryptFinal  
138   EVP_DecryptFinal(myself->cipher_pktctx, outpkt.data + outlen, &outpad);
139    */
140    
141   add_mac_addresses(&outpkt);
142
143   if(write(tap_fd, outpkt.data, outpkt.len) < 0)
144     syslog(LOG_ERR, _("Can't write to tap device: %m"));
145   else
146     total_tap_out += outpkt.len;
147 cp
148   return 0;
149 }
150
151 /*
152   add the given packet of size s to the
153   queue q, be it the send or receive queue
154 */
155 void add_queue(packet_queue_t **q, void *packet, size_t s)
156 {
157   queue_element_t *e;
158 cp
159   e = xmalloc(sizeof(*e));
160   e->packet = xmalloc(s);
161   memcpy(e->packet, packet, s);
162
163   if(!*q)
164     {
165       *q = xmalloc(sizeof(**q));
166       (*q)->head = (*q)->tail = NULL;
167     }
168
169   e->next = NULL;                       /* We insert at the tail */
170
171   if((*q)->tail)                        /* Do we have a tail? */
172     {
173       (*q)->tail->next = e;
174       e->prev = (*q)->tail;
175     }
176   else                                  /* No tail -> no head too */
177     {
178       (*q)->head = e;
179       e->prev = NULL;
180     }
181
182   (*q)->tail = e;
183 cp
184 }
185
186 /* Remove a queue element */
187 void del_queue(packet_queue_t **q, queue_element_t *e)
188 {
189 cp
190   free(e->packet);
191
192   if(e->next)                           /* There is a successor, so we are not tail */
193     {
194       if(e->prev)                       /* There is a predecessor, so we are not head */
195         {
196           e->next->prev = e->prev;
197           e->prev->next = e->next;
198         }
199       else                              /* We are head */
200         {
201           e->next->prev = NULL;
202           (*q)->head = e->next;
203         }
204     }
205   else                                  /* We are tail (or all alone!) */
206     {          
207       if(e->prev)                       /* We are not alone :) */
208         {
209           e->prev->next = NULL;
210           (*q)->tail = e->prev;
211         }
212       else                              /* Adieu */
213         {
214           free(*q);
215           *q = NULL;
216         }
217     }
218     
219   free(e);
220 cp
221 }
222
223 /*
224   flush a queue by calling function for
225   each packet, and removing it when that
226   returned a zero exit code
227 */
228 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
229                  int (*function)(conn_list_t*,void*))
230 {
231   queue_element_t *p, *next = NULL;
232 cp
233   for(p = (*pq)->head; p != NULL; )
234     {
235       next = p->next;
236
237       if(!function(cl, p->packet))
238         del_queue(pq, p);
239         
240       p = next;
241     }
242
243   if(debug_lvl >= DEBUG_TRAFFIC)
244     syslog(LOG_DEBUG, _("Queue flushed"));
245 cp
246 }
247
248 /*
249   flush the send&recv queues
250   void because nothing goes wrong here, packets
251   remain in the queue if something goes wrong
252 */
253 void flush_queues(conn_list_t *cl)
254 {
255 cp
256   if(cl->sq)
257     {
258       if(debug_lvl >= DEBUG_TRAFFIC)
259         syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
260                cl->name, cl->hostname);
261       flush_queue(cl, &(cl->sq), xsend);
262     }
263
264   if(cl->rq)
265     {
266       if(debug_lvl >=  DEBUG_TRAFFIC)
267         syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
268                cl->name, cl->hostname);
269       flush_queue(cl, &(cl->rq), xrecv);
270     }
271 cp
272 }
273
274 /*
275   send a packet to the given vpn ip.
276 */
277 int send_packet(ip_t to, vpn_packet_t *packet)
278 {
279   conn_list_t *cl;
280 cp
281   if((cl = lookup_conn_list_ipv4(to)) == NULL)
282     {
283       if(debug_lvl >= DEBUG_TRAFFIC)
284         {
285           syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
286                  IP_ADDR_V(to));
287         }
288
289       return -1;
290    }
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->ip);
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   set up the local sockets (listen only)
624 */
625 int setup_myself(void)
626 {
627   config_t const *cfg;
628 cp
629   myself = new_conn_list();
630
631   asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
632   myself->flags = 0;
633   myself->protocol_version = PROT_CURRENT;
634
635   if(!(cfg = get_config_val(config, tincname))) /* Not acceptable */
636     {
637       syslog(LOG_ERR, _("Name for tinc daemon required!"));
638       return -1;
639     }
640   else
641     asprintf(&myself->name, "%s", (char*)cfg->data.val);
642
643   if(check_id(myself->name))
644     {
645       syslog(LOG_ERR, _("Invalid name for myself!"));
646       return -1;
647     }
648 cp
649   if(!(cfg = get_config_val(config, privatekey)))
650     {
651       syslog(LOG_ERR, _("Private key for tinc daemon required!"));
652       return -1;
653     }
654   else
655     {
656       myself->rsa_key = RSA_new();
657       BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
658       BN_hex2bn(&myself->rsa_key->e, "FFFF");
659     }
660
661   if(read_host_config(myself))
662     {
663       syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
664       return -1;
665     }
666 cp  
667   if(!(cfg = get_config_val(myself->config, publickey)))
668     {
669       syslog(LOG_ERR, _("Public key for tinc daemon required!"));
670       return -1;
671     }
672   else
673     {
674       BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
675     }
676 /*
677   if(RSA_check_key(myself->rsa_key) != 1)
678     {
679       syslog(LOG_ERR, _("Invalid public/private keypair!"));
680       return -1;
681     }
682 */
683   if(!(cfg = get_config_val(myself->config, port)))
684     myself->port = 655;
685   else
686     myself->port = cfg->data.val;
687
688   if((cfg = get_config_val(myself->config, indirectdata)))
689     if(cfg->data.val == stupid_true)
690       myself->flags |= EXPORTINDIRECTDATA;
691
692   if((cfg = get_config_val(myself->config, tcponly)))
693     if(cfg->data.val == stupid_true)
694       myself->flags |= TCPONLY;
695
696   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
697     {
698       syslog(LOG_ERR, _("Unable to set up a listening socket!"));
699       return -1;
700     }
701
702   if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
703     {
704       syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket!"));
705       close(myself->meta_socket);
706       return -1;
707     }
708
709   myself->status.active = 1;
710
711   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
712 cp
713   return 0;
714 }
715
716 RETSIGTYPE
717 sigalrm_handler(int a)
718 {
719   config_t const *cfg;
720 cp
721   cfg = get_next_config_val(config, connectto, upstreamindex++);
722
723   if(!upstreamindex && !cfg)
724     /* No upstream IP given, we're listen only. */
725     return;
726
727   while(cfg)
728     {
729       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
730         {
731           signal(SIGALRM, SIG_IGN);
732           return;
733         }
734       cfg = get_next_config_val(config, connectto, upstreamindex++); /* Or else we try the next ConnectTo line */
735     }
736
737   signal(SIGALRM, sigalrm_handler);
738   upstreamindex = 0;
739   seconds_till_retry += 5;
740   if(seconds_till_retry > MAXTIMEOUT)    /* Don't wait more than MAXTIMEOUT seconds. */
741     seconds_till_retry = MAXTIMEOUT;
742   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
743          seconds_till_retry);
744   alarm(seconds_till_retry);
745 cp
746 }
747
748 /*
749   setup all initial network connections
750 */
751 int setup_network_connections(void)
752 {
753   config_t const *cfg;
754   char *scriptname;
755 cp
756   if((cfg = get_config_val(config, pingtimeout)) == NULL)
757     timeout = 5;
758   else
759     timeout = cfg->data.val;
760
761   if(setup_tap_fd() < 0)
762     return -1;
763
764   if(setup_myself() < 0)
765     return -1;
766
767   /* Run tinc-up script to further initialize the tap interface */
768
769   asprintf(&scriptname, "%s/tinc-up", confbase);
770
771   if(!fork())
772     {
773
774       execl(scriptname, NULL);
775
776       if(errno != ENOENT)
777         syslog(LOG_WARNING, _("Error while executing %s: %m"), scriptname);
778
779       exit(0);
780     }
781
782   free(scriptname);
783
784   if((cfg = get_next_config_val(config, connectto, upstreamindex++)) == NULL)
785     /* No upstream IP given, we're listen only. */
786     return 0;
787
788   while(cfg)
789     {
790       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
791         return 0;
792       cfg = get_next_config_val(config, connectto, upstreamindex++); /* Or else we try the next ConnectTo line */
793     }
794     
795   signal(SIGALRM, sigalrm_handler);
796   upstreamindex = 0;
797   seconds_till_retry = MAXTIMEOUT;
798   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
799   alarm(seconds_till_retry);
800 cp
801   return 0;
802 }
803
804 /*
805   close all open network connections
806 */
807 void close_network_connections(void)
808 {
809   conn_list_t *p;
810   char *scriptname;
811 cp
812   for(p = conn_list; p != NULL; p = p->next)
813     {
814       if(p->status.dataopen)
815         {
816           shutdown(p->socket, 0); /* No more receptions */
817           close(p->socket);
818         }
819       if(p->status.meta)
820         {
821           send_termreq(p);
822           shutdown(p->meta_socket, 0); /* No more receptions */
823           close(p->meta_socket);
824         }
825     }
826
827   if(myself)
828     if(myself->status.active)
829       {
830         close(myself->meta_socket);
831         close(myself->socket);
832       }
833
834   /* Execute tinc-down script right before shutting down the interface */
835
836   asprintf(&scriptname, "%s/tinc-down", confbase);
837
838   if(!fork())
839     {
840       execl(scriptname, NULL);
841
842       if(errno != ENOENT)
843         syslog(LOG_WARNING, _("Error while executing %s: %m"), scriptname);
844
845       exit(0);
846     }
847       
848   free(scriptname);
849
850   close(tap_fd);
851   destroy_conn_list();
852
853   syslog(LOG_NOTICE, _("Terminating"));
854 cp
855   return;
856 }
857
858 /*
859   create a data (udp) socket
860 */
861 int setup_vpn_connection(conn_list_t *cl)
862 {
863   int nfd, flags;
864   struct sockaddr_in a;
865 cp
866   if(debug_lvl >= DEBUG_TRAFFIC)
867     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
868
869   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
870   if(nfd == -1)
871     {
872       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
873       return -1;
874     }
875
876   a.sin_family = AF_INET;
877   a.sin_port = htons(cl->port);
878   a.sin_addr.s_addr = htonl(cl->address);
879
880   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
881     {
882       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
883              cl->hostname, cl->port);
884       return -1;
885     }
886
887   flags = fcntl(nfd, F_GETFL);
888   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
889     {
890       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
891              cl->name, cl->hostname);
892       return -1;
893     }
894
895   cl->socket = nfd;
896   cl->status.dataopen = 1;
897 cp
898   return 0;
899 }
900
901 /*
902   handle an incoming tcp connect call and open
903   a connection to it.
904 */
905 conn_list_t *create_new_connection(int sfd)
906 {
907   conn_list_t *p;
908   struct sockaddr_in ci;
909   int len = sizeof(ci);
910 cp
911   p = new_conn_list();
912
913   if(getpeername(sfd, &ci, &len) < 0)
914     {
915       syslog(LOG_ERR, _("Error: getpeername: %m"));
916       return NULL;
917     }
918
919   p->name = unknown;
920   p->address = ntohl(ci.sin_addr.s_addr);
921   p->hostname = hostlookup(ci.sin_addr.s_addr);
922   p->meta_socket = sfd;
923   p->status.meta = 1;
924   p->buffer = xmalloc(MAXBUFSIZE);
925   p->buflen = 0;
926   p->last_ping_time = time(NULL);
927   p->want_ping = 0;
928   
929   if(debug_lvl >= DEBUG_CONNECTIONS)
930     syslog(LOG_NOTICE, _("Connection from %s port %d"),
931          p->hostname, htons(ci.sin_port));
932
933   p->allow_request = ID;
934 cp
935   return p;
936 }
937
938 /*
939   put all file descriptors in an fd_set array
940 */
941 void build_fdset(fd_set *fs)
942 {
943   conn_list_t *p;
944 cp
945   FD_ZERO(fs);
946
947   for(p = conn_list; p != NULL; p = p->next)
948     {
949       if(p->status.meta)
950         FD_SET(p->meta_socket, fs);
951       if(p->status.dataopen)
952         FD_SET(p->socket, fs);
953     }
954
955   FD_SET(myself->meta_socket, fs);
956   FD_SET(myself->socket, fs);
957   FD_SET(tap_fd, fs);
958 cp
959 }
960
961 /*
962   receive incoming data from the listening
963   udp socket and write it to the ethertap
964   device after being decrypted
965 */
966 int handle_incoming_vpn_data()
967 {
968   vpn_packet_t pkt;
969   int lenin;
970   int x, l = sizeof(x);
971 cp
972   if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
973     {
974       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
975              __FILE__, __LINE__, myself->socket);
976       return -1;
977     }
978   if(x)
979     {
980       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
981       return -1;
982     }
983
984   if(recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, NULL, NULL) <= 0)
985     {
986       syslog(LOG_ERR, _("Receiving packet failed: %m"));
987       return -1;
988     }
989
990 cp
991   return xrecv(&pkt);
992 }
993
994 /*
995   terminate a connection and notify the other
996   end before closing the sockets
997 */
998 void terminate_connection(conn_list_t *cl)
999 {
1000   conn_list_t *p;
1001
1002 cp
1003   if(cl->status.remove)
1004     return;
1005
1006   if(debug_lvl >= DEBUG_CONNECTIONS)
1007     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1008            cl->name, cl->hostname);
1009  
1010   if(cl->socket)
1011     close(cl->socket);
1012   if(cl->status.meta)
1013     close(cl->meta_socket);
1014
1015   cl->status.remove = 1;
1016
1017   /* If this cl isn't active, don't send any DEL_HOSTs. */
1018
1019 /* FIXME: reprogram this.
1020   if(cl->status.active)
1021     notify_others(cl,NULL,send_del_host);
1022 */
1023     
1024 cp
1025   /* Find all connections that were lost because they were behind cl
1026      (the connection that was dropped). */
1027   if(cl->status.meta)
1028     for(p = conn_list; p != NULL; p = p->next)
1029       {
1030         if((p->nexthop == cl) && (p != cl))
1031           {
1032             if(cl->status.active && p->status.active)
1033 /* FIXME: reprogram this
1034               notify_others(p,cl,send_del_host);
1035 */;
1036            if(cl->socket)
1037              close(cl->socket);
1038             p->status.active = 0;
1039             p->status.remove = 1;
1040           }
1041       }
1042     
1043   cl->status.active = 0;
1044   
1045   if(cl->status.outgoing)
1046     {
1047       signal(SIGALRM, sigalrm_handler);
1048       seconds_till_retry = 5;
1049       alarm(seconds_till_retry);
1050       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1051     }
1052 cp
1053 }
1054
1055 /*
1056   Check if the other end is active.
1057   If we have sent packets, but didn't receive any,
1058   then possibly the other end is dead. We send a
1059   PING request over the meta connection. If the other
1060   end does not reply in time, we consider them dead
1061   and close the connection.
1062 */
1063 int check_dead_connections(void)
1064 {
1065   conn_list_t *p;
1066   time_t now;
1067 cp
1068   now = time(NULL);
1069   for(p = conn_list; p != NULL; p = p->next)
1070     {
1071       if(p->status.remove)
1072         continue;
1073       if(p->status.active && p->status.meta)
1074         {
1075           if(p->last_ping_time + timeout < now)
1076             {
1077               if(p->status.pinged && !p->status.got_pong)
1078                 {
1079                   if(debug_lvl >= DEBUG_PROTOCOL)
1080                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1081                            p->name, p->hostname);
1082                   p->status.timeout = 1;
1083                   terminate_connection(p);
1084                 }
1085               else if(p->want_ping)
1086                 {
1087                   send_ping(p);
1088                   p->last_ping_time = now;
1089                   p->status.pinged = 1;
1090                   p->status.got_pong = 0;
1091                 }
1092             }
1093         }
1094     }
1095 cp
1096   return 0;
1097 }
1098
1099 /*
1100   accept a new tcp connect and create a
1101   new connection
1102 */
1103 int handle_new_meta_connection()
1104 {
1105   conn_list_t *ncn;
1106   struct sockaddr client;
1107   int nfd, len = sizeof(client);
1108 cp
1109   if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1110     {
1111       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1112       return -1;
1113     }
1114
1115   if(!(ncn = create_new_connection(nfd)))
1116     {
1117       shutdown(nfd, 2);
1118       close(nfd);
1119       syslog(LOG_NOTICE, _("Closed attempted connection"));
1120       return 0;
1121     }
1122
1123   ncn->status.meta = 1;
1124   ncn->next = conn_list;
1125   conn_list = ncn;
1126 cp
1127   return 0;
1128 }
1129
1130 /*
1131   check all connections to see if anything
1132   happened on their sockets
1133 */
1134 void check_network_activity(fd_set *f)
1135 {
1136   conn_list_t *p;
1137   int x, l = sizeof(x);
1138 cp
1139   for(p = conn_list; p != NULL; p = p->next)
1140     {
1141       if(p->status.remove)
1142         continue;
1143
1144       if(p->status.dataopen)
1145         if(FD_ISSET(p->socket, f))
1146           {
1147             /*
1148               The only thing that can happen to get us here is apparently an
1149               error on this outgoing(!) UDP socket that isn't immediate (i.e.
1150               something that will not trigger an error directly on send()).
1151               I've once got here when it said `No route to host'.
1152             */
1153             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1154             syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1155                    p->name, p->hostname, strerror(x));
1156             terminate_connection(p);
1157             return;
1158           }  
1159
1160       if(p->status.meta)
1161         if(FD_ISSET(p->meta_socket, f))
1162           if(receive_meta(p) < 0)
1163             {
1164               terminate_connection(p);
1165               return;
1166             } 
1167     }
1168   
1169   if(FD_ISSET(myself->socket, f))
1170     handle_incoming_vpn_data();
1171
1172   if(FD_ISSET(myself->meta_socket, f))
1173     handle_new_meta_connection();
1174 cp
1175 }
1176
1177 /*
1178   read, encrypt and send data that is
1179   available through the ethertap device
1180 */
1181 void handle_tap_input(void)
1182 {
1183   vpn_packet_t vp;
1184   ip_t from, to;
1185   int ether_type, lenin;
1186 cp  
1187   memset(&vp, 0, sizeof(vp));
1188
1189   if(taptype = 1)
1190     {
1191       if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1192         {
1193           syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1194           return;
1195         }
1196       vp.len = lenin;
1197     }
1198   else
1199     {
1200       if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1201         {
1202           syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1203           return;
1204         }
1205       vp.len = lenin - 2;
1206     }
1207
1208   total_tap_in += lenin;
1209
1210   ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1211   if(ether_type != 0x0800)
1212     {
1213       if(debug_lvl >= DEBUG_TRAFFIC)
1214         syslog(LOG_INFO, _("Non-IP ethernet frame %04x from %02x:%02x:%02x:%02x:%02x:%02x"), ether_type, MAC_ADDR_V(vp.data[6]));
1215       return;
1216     }
1217   
1218   if(lenin < 32)
1219     {
1220       if(debug_lvl >= DEBUG_TRAFFIC)
1221         syslog(LOG_INFO, _("Dropping short packet from %02x:%02x:%02x:%02x:%02x:%02x"), MAC_ADDR_V(vp.data[6]));
1222       return;
1223     }
1224
1225   from = ntohl(*((unsigned long*)(&vp.data[26])));
1226   to = ntohl(*((unsigned long*)(&vp.data[30])));
1227
1228   send_packet(to, &vp);
1229 cp
1230 }
1231
1232 /*
1233   this is where it all happens...
1234 */
1235 void main_loop(void)
1236 {
1237   fd_set fset;
1238   struct timeval tv;
1239   int r;
1240   time_t last_ping_check;
1241 cp
1242   last_ping_check = time(NULL);
1243
1244   for(;;)
1245     {
1246       tv.tv_sec = timeout;
1247       tv.tv_usec = 0;
1248
1249       prune_conn_list();
1250       build_fdset(&fset);
1251
1252       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1253         {
1254           if(errno != EINTR) /* because of alarm */
1255             {
1256               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1257               return;
1258             }
1259         }
1260
1261       if(sighup)
1262         {
1263           sighup = 0;
1264 /* FIXME: reprogram this.
1265           if(debug_lvl > 1)
1266             syslog(LOG_INFO, _("Rereading configuration file"));
1267           close_network_connections();
1268           clear_config();
1269           if(read_config_file(&config, configfilename))
1270             {
1271               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1272               exit(0);
1273             }
1274           sleep(5);
1275           setup_network_connections();
1276 */
1277           continue;
1278         }
1279
1280       if(last_ping_check + timeout < time(NULL))
1281         /* Let's check if everybody is still alive */
1282         {
1283           check_dead_connections();
1284           last_ping_check = time(NULL);
1285         }
1286
1287       if(r > 0)
1288         {
1289           check_network_activity(&fset);
1290
1291           /* local tap data */
1292           if(FD_ISSET(tap_fd, &fset))
1293             handle_tap_input();
1294         }
1295     }
1296 cp
1297 }