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