Check for the existance of libdl.
[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 = 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 int send_broadcast(conn_list_t *cl, vpn_packet_t *packet)
308 {
309   conn_list_t *p;
310 cp
311   for(p = cl; p != NULL; p = p->next)
312     if(send_packet(p->real_ip, packet) < 0)
313       {
314         syslog(LOG_ERR, "Could not send a broadcast packet to %08lx (%08lx): %m",
315                p->vpn_ip, p->real_ip);
316         break; /* FIXME: should retry later, and send a ping over the metaconnection. */
317       }
318 cp
319   return 0;
320 }
321
322 /*
323   open the local ethertap device
324 */
325 int setup_tap_fd(void)
326 {
327   int nfd;
328   const char *tapfname;
329   config_t const *cfg;
330 cp  
331   if((cfg = get_config_val(tapdevice)) == NULL)
332     tapfname = "/dev/tap0";
333   else
334     tapfname = cfg->data.ptr;
335
336   if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
337     {
338       syslog(LOG_ERR, "Could not open %s: %m", tapfname);
339       return -1;
340     }
341
342   tap_fd = nfd;
343 cp
344   return 0;
345 }
346
347 /*
348   set up the socket that we listen on for incoming
349   (tcp) connections
350 */
351 int setup_listen_meta_socket(int port)
352 {
353   int nfd, flags;
354   struct sockaddr_in a;
355   const int one = 1;
356 cp
357   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
358     {
359       syslog(LOG_ERR, "Creating metasocket failed: %m");
360       return -1;
361     }
362
363   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
364     {
365       syslog(LOG_ERR, "setsockopt: %m");
366       return -1;
367     }
368
369   flags = fcntl(nfd, F_GETFL);
370   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
371     {
372       syslog(LOG_ERR, "fcntl: %m");
373       return -1;
374     }
375
376   memset(&a, 0, sizeof(a));
377   a.sin_family = AF_INET;
378   a.sin_port = htons(port);
379   a.sin_addr.s_addr = htonl(INADDR_ANY);
380
381   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
382     {
383       syslog(LOG_ERR, "Can't bind to port %hd/tcp: %m", port);
384       return -1;
385     }
386
387   if(listen(nfd, 3))
388     {
389       syslog(LOG_ERR, "listen: %m");
390       return -1;
391     }
392 cp
393   return nfd;
394 }
395
396 /*
397   setup the socket for incoming encrypted
398   data (the udp part)
399 */
400 int setup_vpn_in_socket(int port)
401 {
402   int nfd, flags;
403   struct sockaddr_in a;
404   const int one = 1;
405 cp
406   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
407     {
408       syslog(LOG_ERR, "Creating socket failed: %m");
409       return -1;
410     }
411
412   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
413     {
414       syslog(LOG_ERR, "setsockopt: %m");
415       return -1;
416     }
417
418   flags = fcntl(nfd, F_GETFL);
419   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
420     {
421       syslog(LOG_ERR, "fcntl: %m");
422       return -1;
423     }
424
425   memset(&a, 0, sizeof(a));
426   a.sin_family = AF_INET;
427   a.sin_port = htons(port);
428   a.sin_addr.s_addr = htonl(INADDR_ANY);
429
430   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
431     {
432       syslog(LOG_ERR, "Can't bind to port %hd/udp: %m", port);
433       return -1;
434     }
435 cp
436   return nfd;
437 }
438
439 /*
440   setup an outgoing meta (tcp) socket
441 */
442 int setup_outgoing_meta_socket(conn_list_t *cl)
443 {
444   int flags;
445   struct sockaddr_in a;
446   config_t const *cfg;
447 cp
448   if((cfg = get_config_val(upstreamport)) == NULL)
449     cl->port = 655;
450   else
451     cl->port = cfg->data.val;
452
453   cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
454   if(cl->meta_socket == -1)
455     {
456       syslog(LOG_ERR, "Creating socket failed: %m");
457       return -1;
458     }
459
460   a.sin_family = AF_INET;
461   a.sin_port = htons(cl->port);
462   a.sin_addr.s_addr = htonl(cl->real_ip);
463
464   if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
465     {
466       syslog(LOG_ERR, IP_ADDR_S ":%d: %m", IP_ADDR_V(cl->real_ip), cl->port);
467       return -1;
468     }
469
470   flags = fcntl(cl->meta_socket, F_GETFL);
471   if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
472     {
473       syslog(LOG_ERR, "fcntl: %m");
474       return -1;
475     }
476
477   cl->hostname = hostlookup(htonl(cl->real_ip));
478
479   syslog(LOG_INFO, "Connected to %s:%hd" , cl->hostname, cl->port);
480 cp
481   return 0;
482 }
483
484 /*
485   setup an outgoing connection. It's not
486   necessary to also open an udp socket as
487   well, because the other host will initiate
488   an authentication sequence during which
489   we will do just that.
490 */
491 int setup_outgoing_connection(ip_t ip)
492 {
493   conn_list_t *ncn;
494 cp
495   ncn = new_conn_list();
496   ncn->real_ip = ip;
497
498   if(setup_outgoing_meta_socket(ncn) < 0)
499     {
500       syslog(LOG_ERR, "Could not set up a meta connection.");
501       free_conn_element(ncn);
502       return -1;
503     }
504
505   ncn->status.meta = 1;
506   ncn->status.outgoing = 1;
507   ncn->next = conn_list;
508   conn_list = ncn;
509 cp
510   return 0;
511 }
512
513 /*
514   set up the local sockets (listen only)
515 */
516 int setup_myself(void)
517 {
518   config_t const *cfg;
519 cp
520   myself = new_conn_list();
521
522   if(!(cfg = get_config_val(myvpnip)))
523     {
524       syslog(LOG_ERR, "No value for my VPN IP given");
525       return -1;
526     }
527
528   myself->vpn_ip = cfg->data.ip->ip;
529   myself->vpn_mask = cfg->data.ip->mask;
530
531   if(!(cfg = get_config_val(listenport)))
532     myself->port = 655;
533   else
534     myself->port = cfg->data.val;
535
536   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
537     {
538       syslog(LOG_ERR, "Unable to set up a listening socket");
539       return -1;
540     }
541
542   if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
543     {
544       syslog(LOG_ERR, "Unable to set up an incoming vpn data socket");
545       close(myself->meta_socket);
546       return -1;
547     }
548
549   myself->status.active = 1;
550
551   syslog(LOG_NOTICE, "Ready: listening on port %d.", myself->port);
552 cp
553   return 0;
554 }
555
556 /*
557   setup all initial network connections
558 */
559 int setup_network_connections(void)
560 {
561   config_t const *cfg;
562 cp
563   if((cfg = get_config_val(pingtimeout)) == NULL)
564     timeout = 10;
565   else
566     timeout = cfg->data.val;
567
568   if(setup_tap_fd() < 0)
569     return -1;
570
571   if(setup_myself() < 0)
572     return -1;
573
574   if((cfg = get_config_val(upstreamip)) == NULL)
575     /* No upstream IP given, we're listen only. */
576     return 0;
577
578   if(setup_outgoing_connection(cfg->data.ip->ip))
579     return -1;
580 cp
581   return 0;
582 }
583
584 RETSIGTYPE
585 sigalrm_handler(int a)
586 {
587   config_t const *cfg;
588   static int seconds_till_retry;
589 cp
590   cfg = get_config_val(upstreamip);
591
592   if(!setup_outgoing_connection(cfg->data.ip->ip))
593     {
594       signal(SIGALRM, SIG_IGN);
595       seconds_till_retry = 5;
596     }
597   else
598     {
599       signal(SIGALRM, sigalrm_handler);
600       seconds_till_retry += 5;
601       alarm(seconds_till_retry);
602       syslog(LOG_ERR, "Still failed to connect to other. Will retry in %d seconds.",
603              seconds_till_retry);
604     }
605 cp
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, "Create connection to %08lx:%d failed: %m", ntohs(cl->real_ip),
670              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   
711   syslog(LOG_NOTICE, "Connection from %s:%d", p->hostname, htons(ci.sin_port));
712
713   if(send_basic_info(p) < 0)
714     {
715       free(p);
716       return NULL;
717     }
718 cp
719   return p;
720 }
721
722 /*
723   put all file descriptors in an fd_set array
724 */
725 void build_fdset(fd_set *fs)
726 {
727   conn_list_t *p;
728 cp
729   FD_ZERO(fs);
730
731   for(p = conn_list; p != NULL; p = p->next)
732     {
733       if(p->status.meta)
734         FD_SET(p->meta_socket, fs);
735       if(p->status.dataopen)
736         FD_SET(p->socket, fs);
737     }
738
739   FD_SET(myself->meta_socket, fs);
740   FD_SET(myself->socket, fs);
741   FD_SET(tap_fd, fs);
742 cp
743 }
744
745 /*
746   receive incoming data from the listening
747   udp socket and write it to the ethertap
748   device after being decrypted
749 */
750 int handle_incoming_vpn_data(conn_list_t *cl)
751 {
752   real_packet_t rp;
753   int lenin;
754   int x, l = sizeof(x);
755   conn_list_t *f;
756 cp
757   if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
758     {
759       syslog(LOG_ERR, "This is a bug: %s:%d: %d:%m", __FILE__, __LINE__, cl->socket);
760       return -1;
761     }
762   if(x)
763     {
764       syslog(LOG_ERR, "Incoming data socket error: %s", sys_errlist[x]);
765       return -1;
766     }
767
768   rp.len = -1;
769   lenin = recvfrom(cl->socket, &rp, MTU, 0, NULL, NULL);
770   if(lenin <= 0)
771     {
772       syslog(LOG_ERR, "Receiving data failed: %m");
773       return -1;
774     }
775   total_socket_in += lenin;
776
777   rp.data.len = ntohs(rp.data.len);
778   rp.len = ntohs(rp.len);
779   rp.from = ntohl(rp.from);
780
781   if(rp.len >= 0)
782     {
783       f = lookup_conn(rp.from);
784       if(debug_lvl > 3)
785         syslog(LOG_DEBUG, "packet from " IP_ADDR_S " (len %d)",
786                IP_ADDR_V(rp.from), rp.len);
787       if(!f)
788         {
789           syslog(LOG_ERR, "Got packet from unknown source " IP_ADDR_S,
790                  IP_ADDR_V(rp.from));
791           return -1;
792         }
793
794       if(f->status.validkey)
795         xrecv(f, &rp);
796       else
797         {
798           add_queue(&(f->rq), &rp, rp.len);
799           if(!cl->status.waitingforkey)
800             send_key_request(rp.from);
801         }
802
803       if(my_key_expiry <= time(NULL))
804         regenerate_keys();
805     }
806 cp
807   return 0;
808 }
809
810 /*
811   terminate a connection and notify the other
812   end before closing the sockets
813 */
814 void terminate_connection(conn_list_t *cl)
815 {
816 cp
817   if(cl->status.remove)
818     return;
819
820   if(debug_lvl > 0)
821     syslog(LOG_NOTICE, "Closing connection with %s.", cl->hostname);
822
823   if(cl->status.timeout)
824     send_timeout(cl);
825   else if(!cl->status.termreq)
826     send_termreq(cl);
827
828   close(cl->socket);
829   if(cl->status.meta)
830     close(cl->meta_socket);
831
832   if(cl->status.outgoing)
833     {
834       alarm(5);
835       signal(SIGALRM, sigalrm_handler);
836       syslog(LOG_NOTICE, "Try to re-establish outgoing connection in 5 seconds.");
837     }
838   
839   cl->status.remove = 1;
840 cp
841 }
842
843 /*
844   send out a ping request to all active
845   connections
846 */
847 int send_broadcast_ping(void)
848 {
849   conn_list_t *p;
850 cp
851   for(p = conn_list; p != NULL; p = p->next)
852     {
853       if(p->status.remove)
854         continue;
855       if(p->status.active && p->status.meta)
856         {
857           if(send_ping(p))
858             terminate_connection(p);
859           else
860             {
861               p->status.pinged = 1;
862               p->status.got_pong = 0;
863             }
864         }
865     }
866
867   last_ping_time = time(NULL);
868 cp
869   return 0;
870 }
871
872 /*
873   end all connections that did not respond
874   to the ping probe in time
875 */
876 int check_dead_connections(void)
877 {
878   conn_list_t *p;
879 cp
880   for(p = conn_list; p != NULL; p = p->next)
881     {
882       if(p->status.remove)
883         continue;
884       if(p->status.active && p->status.meta && p->status.pinged && !p->status.got_pong)
885         {
886           syslog(LOG_INFO, "%s (" IP_ADDR_S ") didn't respond to ping",
887                  p->hostname, IP_ADDR_V(p->vpn_ip));
888           p->status.timeout = 1;
889           terminate_connection(p);
890         }
891     }
892 cp
893   return 0;
894 }
895
896 /*
897   accept a new tcp connect and create a
898   new connection
899 */
900 int handle_new_meta_connection(conn_list_t *cl)
901 {
902   conn_list_t *ncn;
903   struct sockaddr client;
904   int nfd, len = sizeof(client);
905 cp
906   if((nfd = accept(cl->meta_socket, &client, &len)) < 0)
907     {
908       syslog(LOG_ERR, "Accepting a new connection failed: %m");
909       return -1;
910     }
911
912   if((ncn = create_new_connection(nfd)) == NULL)
913     {
914       shutdown(nfd, 2);
915       close(nfd);
916       syslog(LOG_NOTICE, "Closed attempted connection.");
917       return 0;
918     }
919
920   ncn->status.meta = 1;
921   ncn->next = conn_list;
922   conn_list = ncn;
923 cp
924   return 0;
925 }
926
927 /*
928   dispatch any incoming meta requests
929 */
930 int handle_incoming_meta_data(conn_list_t *cl)
931 {
932   int x, l = sizeof(x);
933   int request, oldlen, i;
934   int lenin = 0;
935 cp
936   if(getsockopt(cl->meta_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
937     {
938       syslog(LOG_ERR, "This is a bug: %s:%d: %d:%m", __FILE__, __LINE__, cl->meta_socket);
939       return -1;
940     }
941   if(x)
942     {
943       syslog(LOG_ERR, "Metadata socket error: %s", sys_errlist[x]);
944       return -1;
945     }
946
947   if(cl->buflen >= MAXBUFSIZE)
948     {
949       syslog(LOG_ERR, "Metadata read buffer full! Discarding contents.");
950       cl->buflen = 0;
951     }
952
953   lenin = read(cl->meta_socket, cl->buffer, MAXBUFSIZE-cl->buflen);
954
955   if(lenin<=0)
956     {
957       syslog(LOG_ERR, "Metadata socket read error: %m");
958       return -1;
959     }
960
961   oldlen = cl->buflen;
962   cl->buflen += lenin;
963
964   for(;;)
965     {
966       cl->reqlen = 0;
967
968       for(i = oldlen; i < cl->buflen; i++)
969         {
970           if(cl->buffer[i] == '\n')
971             {
972               cl->buffer[i] = 0;  /* replace end-of-line by end-of-string so we can use sscanf */
973               cl->reqlen = i + 1;
974               break;
975             }
976         }
977
978       if(cl->reqlen)
979         {
980           if(sscanf(cl->buffer, "%d", &request) == 1)
981             {
982               if(request_handlers[request] == NULL)
983                 {
984                   syslog(LOG_ERR, "Unknown request: %s", cl->buffer);
985                   return 0;
986                 }
987
988               if(debug_lvl > 3)
989                 syslog(LOG_DEBUG, "Got request: %s", cl->buffer);                             
990
991               request_handlers[request](cl);
992             }
993           else
994             {
995               syslog(LOG_ERR, "Bogus data received: %s", cl->buffer);
996             }
997
998           cl->buflen -= cl->reqlen;
999           memmove(cl->buffer, cl->buffer + cl->reqlen, cl->buflen);
1000           oldlen = 0;
1001         }
1002       else
1003         {
1004           break;
1005         }
1006     }
1007 cp  
1008   return 0;
1009 }
1010
1011 /*
1012   check all connections to see if anything
1013   happened on their sockets
1014 */
1015 void check_network_activity(fd_set *f)
1016 {
1017   conn_list_t *p;
1018   int x, l = sizeof(x);
1019 cp
1020   for(p = conn_list; p != NULL; p = p->next)
1021     {
1022       if(p->status.remove)
1023         continue;
1024
1025       if(p->status.dataopen)
1026         if(FD_ISSET(p->socket, f))
1027           {
1028             /*
1029               The only thing that can happen to get us here is apparently an
1030               error on this outgoing(!) UDP socket that isn't immediate (i.e.
1031               something that will not trigger an error directly on send()).
1032               I've once got here when it said `No route to host'.
1033             */
1034             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1035             syslog(LOG_ERR, "Outgoing data socket error: %s", sys_errlist[x]);
1036             terminate_connection(p);
1037             return;
1038           }  
1039
1040       if(p->status.meta)
1041         if(FD_ISSET(p->meta_socket, f))
1042           if(handle_incoming_meta_data(p) < 0)
1043             {
1044               terminate_connection(p);
1045               return;
1046             } 
1047     }
1048   
1049   if(FD_ISSET(myself->socket, f))
1050     handle_incoming_vpn_data(myself);
1051
1052   if(FD_ISSET(myself->meta_socket, f))
1053     handle_new_meta_connection(myself);
1054 cp
1055 }
1056
1057 /*
1058   read, encrypt and send data that is
1059   available through the ethertap device
1060 */
1061 void handle_tap_input(void)
1062 {
1063   vpn_packet_t vp;
1064   ip_t from, to;
1065   int ether_type, lenin;
1066 cp  
1067   memset(&vp, 0, sizeof(vp));
1068   if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1069     {
1070       syslog(LOG_ERR, "Error while reading from tapdevice: %m");
1071       return;
1072     }
1073
1074   total_tap_in += lenin;
1075
1076   ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1077   if(ether_type != 0x0800)
1078     {
1079       if(debug_lvl > 0)
1080         syslog(LOG_INFO, "Non-IP ethernet frame %04x from " MAC_ADDR_S,
1081                ether_type, MAC_ADDR_V(vp.data[6]));
1082       return;
1083     }
1084   
1085   if(lenin < 32)
1086     {
1087       if(debug_lvl > 0)
1088         syslog(LOG_INFO, "Dropping short packet");
1089       return;
1090     }
1091
1092   from = ntohl(*((unsigned long*)(&vp.data[26])));
1093   to = ntohl(*((unsigned long*)(&vp.data[30])));
1094
1095   if(debug_lvl > 3)
1096     syslog(LOG_DEBUG, "An IP packet (%04x) for " IP_ADDR_S " from " IP_ADDR_S,
1097            ether_type, IP_ADDR_V(to), IP_ADDR_V(from));
1098   if(debug_lvl > 4)
1099     syslog(LOG_DEBUG, MAC_ADDR_S " to " MAC_ADDR_S,
1100            MAC_ADDR_V(vp.data[0]), MAC_ADDR_V(vp.data[6]));
1101   
1102   vp.len = (length_t)lenin - 2;
1103
1104   strip_mac_addresses(&vp);
1105
1106   send_packet(to, &vp);
1107 cp
1108 }
1109
1110 /*
1111   this is where it all happens...
1112 */
1113 void main_loop(void)
1114 {
1115   fd_set fset;
1116   struct timeval tv;
1117   int r;
1118 cp
1119   last_ping_time = 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(r == 0 || last_ping_time + timeout < time(NULL))
1138         /* Timeout... hm... something might be wrong. */
1139         {
1140           check_dead_connections();
1141           send_broadcast_ping();
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 }