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