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