31acd38900a0939d45e73e5f02326314b19f5407
[tinc] / 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.7 2000/06/26 19:39:34 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   syslog(LOG_NOTICE, _("Connection from %s port %d"),
776          p->hostname, htons(ci.sin_port));
777
778   if(send_basic_info(p) < 0)
779     {
780       free(p);
781       return NULL;
782     }
783 cp
784   return p;
785 }
786
787 /*
788   put all file descriptors in an fd_set array
789 */
790 void build_fdset(fd_set *fs)
791 {
792   conn_list_t *p;
793 cp
794   FD_ZERO(fs);
795
796   for(p = conn_list; p != NULL; p = p->next)
797     {
798       if(p->status.meta)
799         FD_SET(p->meta_socket, fs);
800       if(p->status.dataopen)
801         FD_SET(p->socket, fs);
802     }
803
804   FD_SET(myself->meta_socket, fs);
805   FD_SET(myself->socket, fs);
806   FD_SET(tap_fd, fs);
807 cp
808 }
809
810 /*
811   receive incoming data from the listening
812   udp socket and write it to the ethertap
813   device after being decrypted
814 */
815 int handle_incoming_vpn_data(conn_list_t *cl)
816 {
817   real_packet_t rp;
818   int lenin;
819   int x, l = sizeof(x);
820   conn_list_t *f;
821 cp
822   if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
823     {
824       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, cl->socket);
825       return -1;
826     }
827   if(x)
828     {
829       syslog(LOG_ERR, _("Incoming data socket error: %s"), sys_errlist[x]);
830       return -1;
831     }
832
833   rp.len = -1;
834   lenin = recvfrom(cl->socket, &rp, MTU, 0, NULL, NULL);
835   if(lenin <= 0)
836     {
837       syslog(LOG_ERR, _("Receiving packet from %s failed: %m"), cl->hostname);
838       return -1;
839     }
840   total_socket_in += lenin;
841
842   rp.data.len = ntohs(rp.data.len);
843   rp.len = ntohs(rp.len);
844   rp.from = ntohl(rp.from);
845
846   if(rp.len >= 0)
847     {
848       f = lookup_conn(rp.from);
849       if(!f)
850         {
851           syslog(LOG_ERR, _("Got packet from " IP_ADDR_S " (%s) with unknown origin " IP_ADDR_S "?"),
852                  IP_ADDR_V(cl->vpn_ip), cl->hostname, IP_ADDR_V(rp.from));
853           return -1;
854         }
855
856       if(f->status.validkey)
857         xrecv(f, &rp);
858       else
859         {
860           add_queue(&(f->rq), &rp, rp.len);
861           if(!cl->status.waitingforkey)
862             send_key_request(rp.from);
863         }
864
865       if(my_key_expiry <= time(NULL))
866         regenerate_keys();
867     }
868 cp
869   return 0;
870 }
871
872 /*
873   terminate a connection and notify the other
874   end before closing the sockets
875 */
876 void terminate_connection(conn_list_t *cl)
877 {
878   conn_list_t *p, *q;
879
880 cp
881   if(cl->status.remove)
882     return;
883
884   if(debug_lvl > 0)
885     syslog(LOG_NOTICE, _("Closing connection with " IP_ADDR_S " (%s)"),
886            IP_ADDR_V(cl->vpn_ip), cl->hostname);
887
888   if(cl->status.timeout)
889     send_timeout(cl);
890   else if(!cl->status.termreq)
891     send_termreq(cl);
892
893   close(cl->socket);
894   if(cl->status.meta)
895     close(cl->meta_socket);
896
897   if(cl->status.outgoing)
898     {
899       signal(SIGALRM, sigalrm_handler);
900       seconds_till_retry = 5;
901       alarm(seconds_till_retry);
902       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
903     }
904   
905   cl->status.active = 0;
906   cl->status.remove = 1;
907
908 cp
909   /* Find all connections that were lost because they were behind cl
910      (the connection that was dropped). */
911   for(p = conn_list; p != NULL; p = p->next)
912     if(p->nexthop == cl)
913       {
914         p->status.active = 0;
915         p->status.remove = 1;
916       }
917
918 cp 
919   /* Then send a notification about all these connections to all hosts
920      that are still connected to us. */
921   for(p = conn_list; p != NULL; p = p->next)
922     if(!p->status.remove && p->status.meta)
923       for(q = conn_list; q != NULL; q = q->next)
924         if(q->status.remove)
925           send_del_host(p, q);
926
927 cp
928 }
929
930 /*
931   Check if the other end is active.
932   If we have sent packets, but didn't receive any,
933   then possibly the other end is dead. We send a
934   PING request over the meta connection. If the other
935   end does not reply in time, we consider them dead
936   and close the connection.
937 */
938 int check_dead_connections(void)
939 {
940   conn_list_t *p;
941   time_t now;
942 cp
943   now = time(NULL);
944   for(p = conn_list; p != NULL; p = p->next)
945     {
946       if(p->status.remove)
947         continue;
948       if(p->status.active && p->status.meta)
949         {
950           if(p->last_ping_time + timeout < now)
951             {
952               if(p->status.pinged && !p->status.got_pong)
953                 {
954                   if(debug_lvl > 1)
955                     syslog(LOG_INFO, _(IP_ADDR_S " (%s) didn't respond to ping"),
956                            IP_ADDR_V(p->vpn_ip), p->hostname);
957                   p->status.timeout = 1;
958                   terminate_connection(p);
959                 }
960               else if(p->want_ping)
961                 {
962                   send_ping(p);
963                   p->last_ping_time = now;
964                   p->status.pinged = 1;
965                   p->status.got_pong = 0;
966                 }
967             }
968         }
969     }
970 cp
971   return 0;
972 }
973
974 /*
975   accept a new tcp connect and create a
976   new connection
977 */
978 int handle_new_meta_connection(conn_list_t *cl)
979 {
980   conn_list_t *ncn;
981   struct sockaddr client;
982   int nfd, len = sizeof(client);
983 cp
984   if((nfd = accept(cl->meta_socket, &client, &len)) < 0)
985     {
986       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
987       return -1;
988     }
989
990   if((ncn = create_new_connection(nfd)) == NULL)
991     {
992       shutdown(nfd, 2);
993       close(nfd);
994       syslog(LOG_NOTICE, _("Closed attempted connection"));
995       return 0;
996     }
997
998   ncn->status.meta = 1;
999   ncn->next = conn_list;
1000   conn_list = ncn;
1001 cp
1002   return 0;
1003 }
1004
1005 /*
1006   dispatch any incoming meta requests
1007 */
1008 int handle_incoming_meta_data(conn_list_t *cl)
1009 {
1010   int x, l = sizeof(x);
1011   int request, oldlen, i;
1012   int lenin = 0;
1013 cp
1014   if(getsockopt(cl->meta_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1015     {
1016       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, cl->meta_socket);
1017       return -1;
1018     }
1019   if(x)
1020     {
1021       syslog(LOG_ERR, _("Metadata socket error: %s"), sys_errlist[x]);
1022       return -1;
1023     }
1024
1025   if(cl->buflen >= MAXBUFSIZE)
1026     {
1027       syslog(LOG_ERR, _("Metadata read buffer overflow!"));
1028       return -1;
1029     }
1030
1031   lenin = read(cl->meta_socket, cl->buffer, MAXBUFSIZE-cl->buflen);
1032
1033   if(lenin<=0)
1034     {
1035       syslog(LOG_ERR, _("Metadata socket read error: %m"));
1036       return -1;
1037     }
1038
1039   oldlen = cl->buflen;
1040   cl->buflen += lenin;
1041
1042   for(;;)
1043     {
1044       cl->reqlen = 0;
1045
1046       for(i = oldlen; i < cl->buflen; i++)
1047         {
1048           if(cl->buffer[i] == '\n')
1049             {
1050               cl->buffer[i] = 0;  /* replace end-of-line by end-of-string so we can use sscanf */
1051               cl->reqlen = i + 1;
1052               break;
1053             }
1054         }
1055
1056       if(cl->reqlen)
1057         {
1058           if(debug_lvl > 2)
1059             syslog(LOG_DEBUG, _("Got request from " IP_ADDR_S " (%s): %s"),
1060                          IP_ADDR_V(cl->vpn_ip), cl->hostname, cl->buffer);
1061           if(sscanf(cl->buffer, "%d", &request) == 1)
1062             {
1063               if((request < 0) || (request > 255) || (request_handlers[request] == NULL))
1064                 {
1065                   syslog(LOG_ERR, _("Unknown request from " IP_ADDR_S " (%s)"),
1066                          IP_ADDR_V(cl->vpn_ip), cl->hostname);
1067                   return -1;
1068                 }
1069
1070               if(request_handlers[request](cl))  /* Something went wrong. Probably scriptkiddies. Terminate. */
1071                 {
1072                   syslog(LOG_ERR, _("Error while processing request from " IP_ADDR_S " (%s)"),
1073                          IP_ADDR_V(cl->vpn_ip), cl->hostname);
1074                   return -1;
1075                 }
1076             }
1077           else
1078             {
1079               syslog(LOG_ERR, _("Bogus data received from " IP_ADDR_S " (%s)"),
1080                          IP_ADDR_V(cl->vpn_ip), cl->hostname);
1081               return -1;
1082             }
1083
1084           cl->buflen -= cl->reqlen;
1085           memmove(cl->buffer, cl->buffer + cl->reqlen, cl->buflen);
1086           oldlen = 0;
1087         }
1088       else
1089         {
1090           break;
1091         }
1092     }
1093
1094   cl->last_ping_time = time(NULL);
1095   cl->want_ping = 0;
1096 cp  
1097   return 0;
1098 }
1099
1100 /*
1101   check all connections to see if anything
1102   happened on their sockets
1103 */
1104 void check_network_activity(fd_set *f)
1105 {
1106   conn_list_t *p;
1107   int x, l = sizeof(x);
1108 cp
1109   for(p = conn_list; p != NULL; p = p->next)
1110     {
1111       if(p->status.remove)
1112         continue;
1113
1114       if(p->status.dataopen)
1115         if(FD_ISSET(p->socket, f))
1116           {
1117             /*
1118               The only thing that can happen to get us here is apparently an
1119               error on this outgoing(!) UDP socket that isn't immediate (i.e.
1120               something that will not trigger an error directly on send()).
1121               I've once got here when it said `No route to host'.
1122             */
1123             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1124             syslog(LOG_ERR, _("Outgoing data socket error: %s"), sys_errlist[x]);
1125             terminate_connection(p);
1126             return;
1127           }  
1128
1129       if(p->status.meta)
1130         if(FD_ISSET(p->meta_socket, f))
1131           if(handle_incoming_meta_data(p) < 0)
1132             {
1133               terminate_connection(p);
1134               return;
1135             } 
1136     }
1137   
1138   if(FD_ISSET(myself->socket, f))
1139     handle_incoming_vpn_data(myself);
1140
1141   if(FD_ISSET(myself->meta_socket, f))
1142     handle_new_meta_connection(myself);
1143 cp
1144 }
1145
1146 /*
1147   read, encrypt and send data that is
1148   available through the ethertap device
1149 */
1150 void handle_tap_input(void)
1151 {
1152   vpn_packet_t vp;
1153   ip_t from, to;
1154   int ether_type, lenin;
1155 cp  
1156   memset(&vp, 0, sizeof(vp));
1157   if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1158     {
1159       syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1160       return;
1161     }
1162
1163   total_tap_in += lenin;
1164
1165   ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1166   if(ether_type != 0x0800)
1167     {
1168       if(debug_lvl > 3)
1169         syslog(LOG_INFO, _("Non-IP ethernet frame %04x from " MAC_ADDR_S),
1170                ether_type, MAC_ADDR_V(vp.data[6]));
1171       return;
1172     }
1173   
1174   if(lenin < 32)
1175     {
1176       if(debug_lvl > 3)
1177         syslog(LOG_INFO, _("Dropping short packet"));
1178       return;
1179     }
1180
1181   from = ntohl(*((unsigned long*)(&vp.data[26])));
1182   to = ntohl(*((unsigned long*)(&vp.data[30])));
1183
1184   vp.len = (length_t)lenin - 2;
1185
1186   strip_mac_addresses(&vp);
1187
1188   send_packet(to, &vp);
1189 cp
1190 }
1191
1192 /*
1193   this is where it all happens...
1194 */
1195 void main_loop(void)
1196 {
1197   fd_set fset;
1198   struct timeval tv;
1199   int r;
1200   time_t last_ping_check;
1201 cp
1202   last_ping_check = time(NULL);
1203
1204   for(;;)
1205     {
1206       tv.tv_sec = timeout;
1207       tv.tv_usec = 0;
1208
1209       prune_conn_list();
1210       build_fdset(&fset);
1211
1212       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1213         {
1214           if(errno == EINTR) /* because of alarm */
1215             continue;
1216           syslog(LOG_ERR, _("Error while waiting for input: %m"));
1217           return;
1218         }
1219
1220       if(last_ping_check + timeout < time(NULL))
1221         /* Let's check if everybody is still alive */
1222         {
1223           check_dead_connections();
1224           last_ping_check = time(NULL);
1225           continue;
1226         }
1227
1228       check_network_activity(&fset);
1229
1230       /* local tap data */
1231       if(FD_ISSET(tap_fd, &fset))
1232         handle_tap_input();
1233     }
1234 cp
1235 }