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