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