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