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