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