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