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