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