- Moved all connection messages to debug level 1, without -d's only the
[oweals/tinc.git] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998,1999,2000 Ivo Timmermans <itimmermans@bigfoot.com>,
4                             2000 Guus Sliepen <guus@sliepen.warande.net>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: net.c,v 1.35.4.8 2000/06/26 20:30:20 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <arpa/inet.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <netdb.h>
29 #include <netinet/in.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/signal.h>
34 #include <sys/socket.h>
35 #include <sys/time.h>
36 #include <sys/types.h>
37 #include <syslog.h>
38 #include <unistd.h>
39
40 #include <cipher.h>
41 #include <utils.h>
42 #include <xalloc.h>
43
44 #include "conf.h"
45 #include "encr.h"
46 #include "net.h"
47 #include "netutl.h"
48 #include "protocol.h"
49
50 #include "system.h"
51
52 int tap_fd = -1;
53
54 int total_tap_in = 0;
55 int total_tap_out = 0;
56 int total_socket_in = 0;
57 int total_socket_out = 0;
58
59 static int seconds_till_retry;
60
61 /* The global list of existing connections */
62 conn_list_t *conn_list = NULL;
63 conn_list_t *myself = NULL;
64
65 /*
66   strip off the MAC adresses of an ethernet frame
67 */
68 void strip_mac_addresses(vpn_packet_t *p)
69 {
70   unsigned char tmp[MAXSIZE];
71 cp
72   memcpy(tmp, p->data, p->len);
73   p->len -= 12;
74   memcpy(p->data, &tmp[12], p->len);
75 cp
76 }
77
78 /*
79   reassemble MAC addresses
80 */
81 void add_mac_addresses(vpn_packet_t *p)
82 {
83   unsigned char tmp[MAXSIZE];
84 cp
85   memcpy(&tmp[12], p->data, p->len);
86   p->len += 12;
87   tmp[0] = tmp[6] = 0xfe;
88   tmp[1] = tmp[7] = 0xfd;
89   *((ip_t*)(&tmp[2])) = (ip_t)(htonl(myself->vpn_ip));
90   *((ip_t*)(&tmp[8])) = *((ip_t*)(&tmp[26]));
91   memcpy(p->data, &tmp[0], p->len);
92 cp
93 }
94
95 int xsend(conn_list_t *cl, void *packet)
96 {
97   int r;
98   real_packet_t rp;
99 cp
100   do_encrypt((vpn_packet_t*)packet, &rp, cl->key);
101   rp.from = htonl(myself->vpn_ip);
102   rp.data.len = htons(rp.data.len);
103   rp.len = htons(rp.len);
104
105   if(debug_lvl > 3)
106     syslog(LOG_ERR, _("Sending packet of %d bytes to " IP_ADDR_S " (%s)"),
107            ntohs(rp.len), IP_ADDR_V(cl->vpn_ip), cl->hostname);
108
109   if((r = send(cl->socket, (char*)&rp, ntohs(rp.len), 0)) < 0)
110     {
111       syslog(LOG_ERR, _("Error sending packet to " IP_ADDR_S " (%s): %m"),
112              IP_ADDR_V(cl->vpn_ip), cl->hostname);
113       return -1;
114     }
115
116   total_socket_out += r;
117
118   cl->want_ping = 1;
119 cp
120   return 0;
121 }
122
123 int xrecv(conn_list_t *cl, void *packet)
124 {
125   vpn_packet_t vp;
126   int lenin;
127 cp
128   do_decrypt((real_packet_t*)packet, &vp, cl->key);
129   add_mac_addresses(&vp);
130
131   if(debug_lvl > 3)
132     syslog(LOG_ERR, _("Receiving packet of %d bytes from " IP_ADDR_S " (%s)"),
133            ((real_packet_t*)packet)->len, IP_ADDR_V(cl->vpn_ip), cl->hostname);
134
135   if((lenin = write(tap_fd, &vp, vp.len + sizeof(vp.len))) < 0)
136     syslog(LOG_ERR, _("Can't write to tap device: %m"));
137   else
138     total_tap_out += lenin;
139
140   cl->want_ping = 0;
141   cl->last_ping_time = time(NULL);
142 cp
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;
153 cp
154   e = xmalloc(sizeof(*e));
155   e->packet = xmalloc(s);
156   memcpy(e->packet, packet, s);
157
158   if(!*q)
159     {
160       *q = xmalloc(sizeof(**q));
161       (*q)->head = (*q)->tail = NULL;
162     }
163
164   e->next = NULL;                       /* We insert at the tail */
165
166   if((*q)->tail)                        /* Do we have a tail? */
167     {
168       (*q)->tail->next = e;
169       e->prev = (*q)->tail;
170     }
171   else                                  /* No tail -> no head too */
172     {
173       (*q)->head = e;
174       e->prev = NULL;
175     }
176
177   (*q)->tail = e;
178 cp
179 }
180
181 /* Remove a queue element */
182 void del_queue(packet_queue_t **q, queue_element_t *e)
183 {
184 cp
185   free(e->packet);
186
187   if(e->next)                           /* There is a successor, so we are not tail */
188     {
189       if(e->prev)                       /* There is a predecessor, so we are not head */
190         {
191           e->next->prev = e->prev;
192           e->prev->next = e->next;
193         }
194       else                              /* We are head */
195         {
196           e->next->prev = NULL;
197           (*q)->head = e->next;
198         }
199     }
200   else                                  /* We are tail (or all alone!) */
201     {          
202       if(e->prev)                       /* We are not alone :) */
203         {
204           e->prev->next = NULL;
205           (*q)->tail = e->prev;
206         }
207       else                              /* Adieu */
208         {
209           free(*q);
210           *q = NULL;
211         }
212     }
213     
214   free(e);
215 cp
216 }
217
218 /*
219   flush a queue by calling function for
220   each packet, and removing it when that
221   returned a zero exit code
222 */
223 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
224                  int (*function)(conn_list_t*,void*))
225 {
226   queue_element_t *p, *next = NULL;
227 cp
228   for(p = (*pq)->head; p != NULL; )
229     {
230       next = p->next;
231
232       if(!function(cl, p->packet))
233         del_queue(pq, p);
234         
235       p = next;
236     }
237
238   if(debug_lvl > 3)
239     syslog(LOG_DEBUG, _("Queue flushed"));
240 cp
241 }
242
243 /*
244   flush the send&recv queues
245   void because nothing goes wrong here, packets
246   remain in the queue if something goes wrong
247 */
248 void flush_queues(conn_list_t *cl)
249 {
250 cp
251   if(cl->sq)
252     {
253       if(debug_lvl > 3)
254         syslog(LOG_DEBUG, _("Flushing send queue for " IP_ADDR_S),
255                IP_ADDR_V(cl->vpn_ip));
256       flush_queue(cl, &(cl->sq), xsend);
257     }
258
259   if(cl->rq)
260     {
261       if(debug_lvl > 3)
262         syslog(LOG_DEBUG, _("Flushing receive queue for " IP_ADDR_S),
263                IP_ADDR_V(cl->vpn_ip));
264       flush_queue(cl, &(cl->rq), xrecv);
265     }
266 cp
267 }
268
269 /*
270   send a packet to the given vpn ip.
271 */
272 int send_packet(ip_t to, vpn_packet_t *packet)
273 {
274   conn_list_t *cl;
275 cp
276   if((cl = lookup_conn(to)) == NULL)
277     {
278       if(debug_lvl > 3)
279         {
280           syslog(LOG_NOTICE, _("Trying to look up " IP_ADDR_S " in connection list failed!"),
281                  IP_ADDR_V(to));
282         }
283         
284       /* Is this really necessary? If we can't find "to", then neither should any uplink. (GS) */
285       
286       return -1;
287         
288       for(cl = conn_list; cl != NULL && !cl->status.outgoing; cl = cl->next);
289       if(!cl)
290         { /* No open outgoing connection has been found. */
291           if(debug_lvl > 3)
292             syslog(LOG_NOTICE, _("There is no remote host I can send this packet to!"));
293           return -1;
294         }
295     }
296     
297   /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
298   
299   if(myself->flags & EXPORTINDIRECTDATA)
300     {
301       for(cl = conn_list; cl != NULL && !cl->status.outgoing; cl = cl->next);
302       if(!cl)
303         { /* No open outgoing connection has been found. */
304           if(debug_lvl > 3)
305             syslog(LOG_NOTICE, _("There is no remote host I can send this packet to!"));
306           return -1;
307         }
308     }
309   else
310
311   /* If indirectdata flag is set for the destination we just looked up,
312    * then real_ip is actually the vpn_ip of the gateway tincd
313    * it is behind.
314    */
315    
316   if(cl->flags & INDIRECTDATA)
317     {
318       if(debug_lvl > 3)
319         syslog(LOG_NOTICE, _("Indirect packet to " IP_ADDR_S " via " IP_ADDR_S),
320                IP_ADDR_V(cl->vpn_ip), IP_ADDR_V(cl->real_ip));
321       if((cl = lookup_conn(cl->real_ip)) == NULL)
322         {
323           if(debug_lvl > 3)
324               syslog(LOG_NOTICE, _("Indirect look up " IP_ADDR_S " in connection list failed!"),
325                      IP_ADDR_V(to));
326             
327           /* Gateway tincd dead? Should we kill it? (GS) */
328
329           return -1;
330         }
331       if(cl->flags & INDIRECTDATA)  /* This should not happen */
332         {
333           if(debug_lvl > 3)
334               syslog(LOG_NOTICE, _("Double indirection for " IP_ADDR_S),
335                      IP_ADDR_V(to));
336           return -1;        
337         }
338     }            
339
340   if(my_key_expiry <= time(NULL))
341     regenerate_keys();
342
343   if(!cl->status.dataopen)
344     if(setup_vpn_connection(cl) < 0)
345       {
346         syslog(LOG_ERR, _("Could not open UDP connection to " IP_ADDR_S " (%s)"), IP_ADDR_V(cl->vpn_ip), cl->hostname);
347         return -1;
348       }
349       
350   if(!cl->status.validkey)
351     {
352       if(debug_lvl > 3)
353         syslog(LOG_INFO, _(IP_ADDR_S " (%s) has no valid key, queueing packet"), IP_ADDR_V(cl->vpn_ip), cl->hostname);
354       add_queue(&(cl->sq), packet, packet->len + 2);
355       if(!cl->status.waitingforkey)
356         send_key_request(cl->vpn_ip);                   /* Keys should be sent to the host running the tincd */
357       return 0;
358     }
359
360   if(!cl->status.active)
361     {
362       if(debug_lvl > 3)
363         syslog(LOG_INFO, _(IP_ADDR_S " (%s) is not ready, queueing packet"), IP_ADDR_V(cl->vpn_ip), cl->hostname);
364       add_queue(&(cl->sq), packet, packet->len + 2);
365       return 0; /* We don't want to mess up, do we? */
366     }
367
368   /* can we send it? can we? can we? huh? */
369 cp
370   return xsend(cl, packet);
371 }
372
373 /*
374   open the local ethertap device
375 */
376 int setup_tap_fd(void)
377 {
378   int nfd;
379   const char *tapfname;
380   config_t const *cfg;
381 cp  
382   if((cfg = get_config_val(tapdevice)) == NULL)
383     tapfname = "/dev/tap0";
384   else
385     tapfname = cfg->data.ptr;
386
387   if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
388     {
389       syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
390       return -1;
391     }
392
393   tap_fd = nfd;
394 cp
395   return 0;
396 }
397
398 /*
399   set up the socket that we listen on for incoming
400   (tcp) connections
401 */
402 int setup_listen_meta_socket(int port)
403 {
404   int nfd, flags;
405   struct sockaddr_in a;
406   const int one = 1;
407 cp
408   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
409     {
410       syslog(LOG_ERR, _("Creating metasocket failed: %m"));
411       return -1;
412     }
413
414   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
415     {
416       syslog(LOG_ERR, _("setsockopt: %m"));
417       return -1;
418     }
419
420   flags = fcntl(nfd, F_GETFL);
421   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
422     {
423       syslog(LOG_ERR, _("fcntl: %m"));
424       return -1;
425     }
426
427   memset(&a, 0, sizeof(a));
428   a.sin_family = AF_INET;
429   a.sin_port = htons(port);
430   a.sin_addr.s_addr = htonl(INADDR_ANY);
431
432   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
433     {
434       syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
435       return -1;
436     }
437
438   if(listen(nfd, 3))
439     {
440       syslog(LOG_ERR, _("listen: %m"));
441       return -1;
442     }
443 cp
444   return nfd;
445 }
446
447 /*
448   setup the socket for incoming encrypted
449   data (the udp part)
450 */
451 int setup_vpn_in_socket(int port)
452 {
453   int nfd, flags;
454   struct sockaddr_in a;
455   const int one = 1;
456 cp
457   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
458     {
459       syslog(LOG_ERR, _("Creating socket failed: %m"));
460       return -1;
461     }
462
463   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
464     {
465       syslog(LOG_ERR, _("setsockopt: %m"));
466       return -1;
467     }
468
469   flags = fcntl(nfd, F_GETFL);
470   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
471     {
472       syslog(LOG_ERR, _("fcntl: %m"));
473       return -1;
474     }
475
476   memset(&a, 0, sizeof(a));
477   a.sin_family = AF_INET;
478   a.sin_port = htons(port);
479   a.sin_addr.s_addr = htonl(INADDR_ANY);
480
481   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
482     {
483       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
484       return -1;
485     }
486 cp
487   return nfd;
488 }
489
490 /*
491   setup an outgoing meta (tcp) socket
492 */
493 int setup_outgoing_meta_socket(conn_list_t *cl)
494 {
495   int flags;
496   struct sockaddr_in a;
497   config_t const *cfg;
498 cp
499   if((cfg = get_config_val(upstreamport)) == NULL)
500     cl->port = 655;
501   else
502     cl->port = cfg->data.val;
503
504   cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
505   if(cl->meta_socket == -1)
506     {
507       syslog(LOG_ERR, _("Creating socket failed: %m"));
508       return -1;
509     }
510
511   a.sin_family = AF_INET;
512   a.sin_port = htons(cl->port);
513   a.sin_addr.s_addr = htonl(cl->real_ip);
514
515   if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
516     {
517       syslog(LOG_ERR, _(IP_ADDR_S ":%d: %m"), IP_ADDR_V(cl->real_ip), cl->port);
518       return -1;
519     }
520
521   flags = fcntl(cl->meta_socket, F_GETFL);
522   if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
523     {
524       syslog(LOG_ERR, _("fcntl: %m"));
525       return -1;
526     }
527
528   syslog(LOG_INFO, _("Connected to " IP_ADDR_S ":%hd"),
529          IP_ADDR_V(cl->real_ip), cl->port);
530 cp
531   return 0;
532 }
533
534 /*
535   setup an outgoing connection. It's not
536   necessary to also open an udp socket as
537   well, because the other host will initiate
538   an authentication sequence during which
539   we will do just that.
540 */
541 int setup_outgoing_connection(ip_t ip)
542 {
543   conn_list_t *ncn;
544 cp
545   ncn = new_conn_list();
546   ncn->real_ip = ip;
547   ncn->hostname = hostlookup(htonl(ip));
548   
549   if(setup_outgoing_meta_socket(ncn) < 0)
550     {
551       syslog(LOG_ERR, _("Could not set up a meta connection!"));
552       free_conn_element(ncn);
553       return -1;
554     }
555
556   ncn->status.meta = 1;
557   ncn->status.outgoing = 1;
558   ncn->next = conn_list;
559   conn_list = ncn;
560 cp
561   return 0;
562 }
563
564 /*
565   set up the local sockets (listen only)
566 */
567 int setup_myself(void)
568 {
569   config_t const *cfg;
570 cp
571   myself = new_conn_list();
572
573   if(!(cfg = get_config_val(myvpnip)))
574     {
575       syslog(LOG_ERR, _("No value for my VPN IP given"));
576       return -1;
577     }
578
579   myself->vpn_ip = cfg->data.ip->ip;
580   myself->hostname = hostlookup(htonl(myself->vpn_ip));
581   myself->vpn_mask = cfg->data.ip->mask;
582   myself->flags = 0;
583
584   if(!(cfg = get_config_val(listenport)))
585     myself->port = 655;
586   else
587     myself->port = cfg->data.val;
588
589   if(cfg = get_config_val(indirectdata))
590     if(cfg->data.val)
591       myself->flags |= EXPORTINDIRECTDATA;
592
593   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
594     {
595       syslog(LOG_ERR, _("Unable to set up a listening socket"));
596       return -1;
597     }
598
599   if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
600     {
601       syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket"));
602       close(myself->meta_socket);
603       return -1;
604     }
605
606   myself->status.active = 1;
607
608   syslog(LOG_NOTICE, _("Ready: listening on port %d"), myself->port);
609 cp
610   return 0;
611 }
612
613 RETSIGTYPE
614 sigalrm_handler(int a)
615 {
616   config_t const *cfg;
617 cp
618   cfg = get_config_val(upstreamip);
619
620   if(!setup_outgoing_connection(cfg->data.ip->ip))
621     {
622       signal(SIGALRM, SIG_IGN);
623     }
624   else
625     {
626       signal(SIGALRM, sigalrm_handler);
627       seconds_till_retry += 5;
628       if(seconds_till_retry>300)    /* Don't wait more than 5 minutes. */
629         seconds_till_retry = 300;
630       alarm(seconds_till_retry);
631       syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
632              seconds_till_retry);
633     }
634 cp
635 }
636
637 /*
638   setup all initial network connections
639 */
640 int setup_network_connections(void)
641 {
642   config_t const *cfg;
643 cp
644   if((cfg = get_config_val(pingtimeout)) == NULL)
645     timeout = 5;
646   else
647     timeout = cfg->data.val;
648
649   if(setup_tap_fd() < 0)
650     return -1;
651
652   if(setup_myself() < 0)
653     return -1;
654
655   if((cfg = get_config_val(upstreamip)) == NULL)
656     /* No upstream IP given, we're listen only. */
657     return 0;
658
659   if(setup_outgoing_connection(cfg->data.ip->ip))
660     {
661       signal(SIGALRM, sigalrm_handler);
662       seconds_till_retry = 300;
663       alarm(seconds_till_retry);
664       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 minutes"));
665     }
666 cp
667   return 0;
668 }
669
670 /*
671   close all open network connections
672 */
673 void close_network_connections(void)
674 {
675   conn_list_t *p;
676 cp
677   for(p = conn_list; p != NULL; p = p->next)
678     {
679       if(p->status.dataopen)
680         {
681           shutdown(p->socket, 0); /* No more receptions */
682           close(p->socket);
683         }
684       if(p->status.meta)
685         {
686           send_termreq(p);
687           shutdown(p->meta_socket, 0); /* No more receptions */
688           close(p->meta_socket);
689         }
690     }
691
692   if(myself)
693     if(myself->status.active)
694       {
695         close(myself->meta_socket);
696         close(myself->socket);
697       }
698
699   close(tap_fd);
700   destroy_conn_list();
701
702   syslog(LOG_NOTICE, _("Terminating"));
703 cp
704   return;
705 }
706
707 /*
708   create a data (udp) socket
709 */
710 int setup_vpn_connection(conn_list_t *cl)
711 {
712   int nfd, flags;
713   struct sockaddr_in a;
714 cp
715   if(debug_lvl > 0)
716     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
717
718   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
719   if(nfd == -1)
720     {
721       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
722       return -1;
723     }
724
725   a.sin_family = AF_INET;
726   a.sin_port = htons(cl->port);
727   a.sin_addr.s_addr = htonl(cl->real_ip);
728
729   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
730     {
731       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
732              cl->hostname, cl->port);
733       return -1;
734     }
735
736   flags = fcntl(nfd, F_GETFL);
737   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
738     {
739       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, nfd);
740       return -1;
741     }
742
743   cl->socket = nfd;
744   cl->status.dataopen = 1;
745 cp
746   return 0;
747 }
748
749 /*
750   handle an incoming tcp connect call and open
751   a connection to it.
752 */
753 conn_list_t *create_new_connection(int sfd)
754 {
755   conn_list_t *p;
756   struct sockaddr_in ci;
757   int len = sizeof(ci);
758 cp
759   p = new_conn_list();
760
761   if(getpeername(sfd, &ci, &len) < 0)
762     {
763       syslog(LOG_ERR, _("Error: getpeername: %m"));
764       return NULL;
765     }
766
767   p->real_ip = ntohl(ci.sin_addr.s_addr);
768   p->hostname = hostlookup(ci.sin_addr.s_addr);
769   p->meta_socket = sfd;
770   p->status.meta = 1;
771   p->buflen = 0;
772   p->last_ping_time = time(NULL);
773   p->want_ping = 0;
774   
775   if(debug_lvl > 0)
776     syslog(LOG_NOTICE, _("Connection from %s port %d"),
777          p->hostname, htons(ci.sin_port));
778
779   if(send_basic_info(p) < 0)
780     {
781       free(p);
782       return NULL;
783     }
784 cp
785   return p;
786 }
787
788 /*
789   put all file descriptors in an fd_set array
790 */
791 void build_fdset(fd_set *fs)
792 {
793   conn_list_t *p;
794 cp
795   FD_ZERO(fs);
796
797   for(p = conn_list; p != NULL; p = p->next)
798     {
799       if(p->status.meta)
800         FD_SET(p->meta_socket, fs);
801       if(p->status.dataopen)
802         FD_SET(p->socket, fs);
803     }
804
805   FD_SET(myself->meta_socket, fs);
806   FD_SET(myself->socket, fs);
807   FD_SET(tap_fd, fs);
808 cp
809 }
810
811 /*
812   receive incoming data from the listening
813   udp socket and write it to the ethertap
814   device after being decrypted
815 */
816 int handle_incoming_vpn_data(conn_list_t *cl)
817 {
818   real_packet_t rp;
819   int lenin;
820   int x, l = sizeof(x);
821   conn_list_t *f;
822 cp
823   if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
824     {
825       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, cl->socket);
826       return -1;
827     }
828   if(x)
829     {
830       syslog(LOG_ERR, _("Incoming data socket error: %s"), sys_errlist[x]);
831       return -1;
832     }
833
834   rp.len = -1;
835   lenin = recvfrom(cl->socket, &rp, MTU, 0, NULL, NULL);
836   if(lenin <= 0)
837     {
838       syslog(LOG_ERR, _("Receiving packet from %s failed: %m"), cl->hostname);
839       return -1;
840     }
841   total_socket_in += lenin;
842
843   rp.data.len = ntohs(rp.data.len);
844   rp.len = ntohs(rp.len);
845   rp.from = ntohl(rp.from);
846
847   if(rp.len >= 0)
848     {
849       f = lookup_conn(rp.from);
850       if(!f)
851         {
852           syslog(LOG_ERR, _("Got packet from " IP_ADDR_S " (%s) with unknown origin " IP_ADDR_S "?"),
853                  IP_ADDR_V(cl->vpn_ip), cl->hostname, IP_ADDR_V(rp.from));
854           return -1;
855         }
856
857       if(f->status.validkey)
858         xrecv(f, &rp);
859       else
860         {
861           add_queue(&(f->rq), &rp, rp.len);
862           if(!cl->status.waitingforkey)
863             send_key_request(rp.from);
864         }
865
866       if(my_key_expiry <= time(NULL))
867         regenerate_keys();
868     }
869 cp
870   return 0;
871 }
872
873 /*
874   terminate a connection and notify the other
875   end before closing the sockets
876 */
877 void terminate_connection(conn_list_t *cl)
878 {
879   conn_list_t *p, *q;
880
881 cp
882   if(cl->status.remove)
883     return;
884
885   if(debug_lvl > 0)
886     syslog(LOG_NOTICE, _("Closing connection with " IP_ADDR_S " (%s)"),
887            IP_ADDR_V(cl->vpn_ip), cl->hostname);
888
889   if(cl->status.timeout)
890     send_timeout(cl);
891   else if(!cl->status.termreq)
892     send_termreq(cl);
893
894   close(cl->socket);
895   if(cl->status.meta)
896     close(cl->meta_socket);
897
898   if(cl->status.outgoing)
899     {
900       signal(SIGALRM, sigalrm_handler);
901       seconds_till_retry = 5;
902       alarm(seconds_till_retry);
903       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
904     }
905   
906   cl->status.remove = 1;
907
908   /* If this cl isn't active, don't send any DEL_HOSTs and don't bother
909      checking for other lost connections. */
910   if(!cl->status.active)
911     return;
912     
913   cl->status.active = 0;
914
915 cp
916   /* Find all connections that were lost because they were behind cl
917      (the connection that was dropped). */
918   for(p = conn_list; p != NULL; p = p->next)
919     if(p->nexthop == cl)
920       {
921         p->status.active = 0;
922         p->status.remove = 1;
923       }
924
925 cp 
926   /* Then send a notification about all these connections to all hosts
927      that are still connected to us. */
928   for(p = conn_list; p != NULL; p = p->next)
929     if(!p->status.remove && p->status.meta)
930       for(q = conn_list; q != NULL; q = q->next)
931         if(q->status.remove)
932           send_del_host(p, q);
933
934 cp
935 }
936
937 /*
938   Check if the other end is active.
939   If we have sent packets, but didn't receive any,
940   then possibly the other end is dead. We send a
941   PING request over the meta connection. If the other
942   end does not reply in time, we consider them dead
943   and close the connection.
944 */
945 int check_dead_connections(void)
946 {
947   conn_list_t *p;
948   time_t now;
949 cp
950   now = time(NULL);
951   for(p = conn_list; p != NULL; p = p->next)
952     {
953       if(p->status.remove)
954         continue;
955       if(p->status.active && p->status.meta)
956         {
957           if(p->last_ping_time + timeout < now)
958             {
959               if(p->status.pinged && !p->status.got_pong)
960                 {
961                   if(debug_lvl > 1)
962                     syslog(LOG_INFO, _(IP_ADDR_S " (%s) didn't respond to ping"),
963                            IP_ADDR_V(p->vpn_ip), p->hostname);
964                   p->status.timeout = 1;
965                   terminate_connection(p);
966                 }
967               else if(p->want_ping)
968                 {
969                   send_ping(p);
970                   p->last_ping_time = now;
971                   p->status.pinged = 1;
972                   p->status.got_pong = 0;
973                 }
974             }
975         }
976     }
977 cp
978   return 0;
979 }
980
981 /*
982   accept a new tcp connect and create a
983   new connection
984 */
985 int handle_new_meta_connection(conn_list_t *cl)
986 {
987   conn_list_t *ncn;
988   struct sockaddr client;
989   int nfd, len = sizeof(client);
990 cp
991   if((nfd = accept(cl->meta_socket, &client, &len)) < 0)
992     {
993       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
994       return -1;
995     }
996
997   if((ncn = create_new_connection(nfd)) == NULL)
998     {
999       shutdown(nfd, 2);
1000       close(nfd);
1001       syslog(LOG_NOTICE, _("Closed attempted connection"));
1002       return 0;
1003     }
1004
1005   ncn->status.meta = 1;
1006   ncn->next = conn_list;
1007   conn_list = ncn;
1008 cp
1009   return 0;
1010 }
1011
1012 /*
1013   dispatch any incoming meta requests
1014 */
1015 int handle_incoming_meta_data(conn_list_t *cl)
1016 {
1017   int x, l = sizeof(x);
1018   int request, oldlen, i;
1019   int lenin = 0;
1020 cp
1021   if(getsockopt(cl->meta_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1022     {
1023       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, cl->meta_socket);
1024       return -1;
1025     }
1026   if(x)
1027     {
1028       syslog(LOG_ERR, _("Metadata socket error: %s"), sys_errlist[x]);
1029       return -1;
1030     }
1031
1032   if(cl->buflen >= MAXBUFSIZE)
1033     {
1034       syslog(LOG_ERR, _("Metadata read buffer overflow!"));
1035       return -1;
1036     }
1037
1038   lenin = read(cl->meta_socket, cl->buffer, MAXBUFSIZE-cl->buflen);
1039
1040   if(lenin<=0)
1041     {
1042       syslog(LOG_ERR, _("Metadata socket read error: %m"));
1043       return -1;
1044     }
1045
1046   oldlen = cl->buflen;
1047   cl->buflen += lenin;
1048
1049   for(;;)
1050     {
1051       cl->reqlen = 0;
1052
1053       for(i = oldlen; i < cl->buflen; i++)
1054         {
1055           if(cl->buffer[i] == '\n')
1056             {
1057               cl->buffer[i] = 0;  /* replace end-of-line by end-of-string so we can use sscanf */
1058               cl->reqlen = i + 1;
1059               break;
1060             }
1061         }
1062
1063       if(cl->reqlen)
1064         {
1065           if(debug_lvl > 2)
1066             syslog(LOG_DEBUG, _("Got request from " IP_ADDR_S " (%s): %s"),
1067                          IP_ADDR_V(cl->vpn_ip), cl->hostname, cl->buffer);
1068           if(sscanf(cl->buffer, "%d", &request) == 1)
1069             {
1070               if((request < 0) || (request > 255) || (request_handlers[request] == NULL))
1071                 {
1072                   syslog(LOG_ERR, _("Unknown request from " IP_ADDR_S " (%s)"),
1073                          IP_ADDR_V(cl->vpn_ip), cl->hostname);
1074                   return -1;
1075                 }
1076
1077               if(request_handlers[request](cl))  /* Something went wrong. Probably scriptkiddies. Terminate. */
1078                 {
1079                   syslog(LOG_ERR, _("Error while processing request from " IP_ADDR_S " (%s)"),
1080                          IP_ADDR_V(cl->vpn_ip), cl->hostname);
1081                   return -1;
1082                 }
1083             }
1084           else
1085             {
1086               syslog(LOG_ERR, _("Bogus data received from " IP_ADDR_S " (%s)"),
1087                          IP_ADDR_V(cl->vpn_ip), cl->hostname);
1088               return -1;
1089             }
1090
1091           cl->buflen -= cl->reqlen;
1092           memmove(cl->buffer, cl->buffer + cl->reqlen, cl->buflen);
1093           oldlen = 0;
1094         }
1095       else
1096         {
1097           break;
1098         }
1099     }
1100
1101   cl->last_ping_time = time(NULL);
1102   cl->want_ping = 0;
1103 cp  
1104   return 0;
1105 }
1106
1107 /*
1108   check all connections to see if anything
1109   happened on their sockets
1110 */
1111 void check_network_activity(fd_set *f)
1112 {
1113   conn_list_t *p;
1114   int x, l = sizeof(x);
1115 cp
1116   for(p = conn_list; p != NULL; p = p->next)
1117     {
1118       if(p->status.remove)
1119         continue;
1120
1121       if(p->status.dataopen)
1122         if(FD_ISSET(p->socket, f))
1123           {
1124             /*
1125               The only thing that can happen to get us here is apparently an
1126               error on this outgoing(!) UDP socket that isn't immediate (i.e.
1127               something that will not trigger an error directly on send()).
1128               I've once got here when it said `No route to host'.
1129             */
1130             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1131             syslog(LOG_ERR, _("Outgoing data socket error: %s"), sys_errlist[x]);
1132             terminate_connection(p);
1133             return;
1134           }  
1135
1136       if(p->status.meta)
1137         if(FD_ISSET(p->meta_socket, f))
1138           if(handle_incoming_meta_data(p) < 0)
1139             {
1140               terminate_connection(p);
1141               return;
1142             } 
1143     }
1144   
1145   if(FD_ISSET(myself->socket, f))
1146     handle_incoming_vpn_data(myself);
1147
1148   if(FD_ISSET(myself->meta_socket, f))
1149     handle_new_meta_connection(myself);
1150 cp
1151 }
1152
1153 /*
1154   read, encrypt and send data that is
1155   available through the ethertap device
1156 */
1157 void handle_tap_input(void)
1158 {
1159   vpn_packet_t vp;
1160   ip_t from, to;
1161   int ether_type, lenin;
1162 cp  
1163   memset(&vp, 0, sizeof(vp));
1164   if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1165     {
1166       syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1167       return;
1168     }
1169
1170   total_tap_in += lenin;
1171
1172   ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1173   if(ether_type != 0x0800)
1174     {
1175       if(debug_lvl > 3)
1176         syslog(LOG_INFO, _("Non-IP ethernet frame %04x from " MAC_ADDR_S),
1177                ether_type, MAC_ADDR_V(vp.data[6]));
1178       return;
1179     }
1180   
1181   if(lenin < 32)
1182     {
1183       if(debug_lvl > 3)
1184         syslog(LOG_INFO, _("Dropping short packet"));
1185       return;
1186     }
1187
1188   from = ntohl(*((unsigned long*)(&vp.data[26])));
1189   to = ntohl(*((unsigned long*)(&vp.data[30])));
1190
1191   vp.len = (length_t)lenin - 2;
1192
1193   strip_mac_addresses(&vp);
1194
1195   send_packet(to, &vp);
1196 cp
1197 }
1198
1199 /*
1200   this is where it all happens...
1201 */
1202 void main_loop(void)
1203 {
1204   fd_set fset;
1205   struct timeval tv;
1206   int r;
1207   time_t last_ping_check;
1208 cp
1209   last_ping_check = time(NULL);
1210
1211   for(;;)
1212     {
1213       tv.tv_sec = timeout;
1214       tv.tv_usec = 0;
1215
1216       prune_conn_list();
1217       build_fdset(&fset);
1218
1219       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1220         {
1221           if(errno == EINTR) /* because of alarm */
1222             continue;
1223           syslog(LOG_ERR, _("Error while waiting for input: %m"));
1224           return;
1225         }
1226
1227       if(last_ping_check + timeout < time(NULL))
1228         /* Let's check if everybody is still alive */
1229         {
1230           check_dead_connections();
1231           last_ping_check = time(NULL);
1232           continue;
1233         }
1234
1235       check_network_activity(&fset);
1236
1237       /* local tap data */
1238       if(FD_ISSET(tap_fd, &fset))
1239         handle_tap_input();
1240     }
1241 cp
1242 }