- Fixed indirectdata=no problem
[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.9 2000/06/27 15:08: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, _("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 to %s"),
552              ncn->hostname);
553       free_conn_element(ncn);
554       return -1;
555     }
556
557   ncn->status.meta = 1;
558   ncn->status.outgoing = 1;
559   ncn->next = conn_list;
560   conn_list = ncn;
561 cp
562   return 0;
563 }
564
565 /*
566   set up the local sockets (listen only)
567 */
568 int setup_myself(void)
569 {
570   config_t const *cfg;
571 cp
572   myself = new_conn_list();
573
574   if(!(cfg = get_config_val(myvpnip)))
575     {
576       syslog(LOG_ERR, _("No value for my VPN IP given"));
577       return -1;
578     }
579
580   myself->vpn_ip = cfg->data.ip->ip;
581   myself->hostname = hostlookup(htonl(myself->vpn_ip));
582   myself->vpn_mask = cfg->data.ip->mask;
583   myself->flags = 0;
584
585   if(!(cfg = get_config_val(listenport)))
586     myself->port = 655;
587   else
588     myself->port = cfg->data.val;
589
590   if(cfg = get_config_val(indirectdata))
591     if(cfg->data.val == stupid_true)
592       myself->flags |= EXPORTINDIRECTDATA;
593
594   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
595     {
596       syslog(LOG_ERR, _("Unable to set up a listening socket"));
597       return -1;
598     }
599
600   if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
601     {
602       syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket"));
603       close(myself->meta_socket);
604       return -1;
605     }
606
607   myself->status.active = 1;
608
609   syslog(LOG_NOTICE, _("Ready: listening on port %d"), myself->port);
610 cp
611   return 0;
612 }
613
614 RETSIGTYPE
615 sigalrm_handler(int a)
616 {
617   config_t const *cfg;
618   int index = 1;
619 cp
620   cfg = get_config_val(upstreamip);
621
622   while(cfg)
623     {
624       if(!setup_outgoing_connection(cfg->data.ip->ip))   /* function returns 0 when there are no problems */
625         {
626           signal(SIGALRM, SIG_IGN);
627           return;
628         }
629       cfg = get_next_config_val(upstreamip, index++); /* Or else we try the next ConnectTo line */
630     }
631
632   signal(SIGALRM, sigalrm_handler);
633   seconds_till_retry += 5;
634   if(seconds_till_retry>300)    /* Don't wait more than 5 minutes. */
635     seconds_till_retry = 300;
636   alarm(seconds_till_retry);
637   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
638          seconds_till_retry);
639 cp
640 }
641
642 /*
643   setup all initial network connections
644 */
645 int setup_network_connections(void)
646 {
647   config_t const *cfg;
648   int index = 1;
649 cp
650   if((cfg = get_config_val(pingtimeout)) == NULL)
651     timeout = 5;
652   else
653     timeout = cfg->data.val;
654
655   if(setup_tap_fd() < 0)
656     return -1;
657
658   if(setup_myself() < 0)
659     return -1;
660
661   if((cfg = get_config_val(upstreamip)) == NULL)
662     /* No upstream IP given, we're listen only. */
663     return 0;
664
665   while(cfg)
666     {
667       if(!setup_outgoing_connection(cfg->data.ip->ip))   /* function returns 0 when there are no problems */
668         return 0;
669       cfg = get_next_config_val(upstreamip, index++); /* Or else we try the next ConnectTo line */
670     }
671     
672   signal(SIGALRM, sigalrm_handler);
673   seconds_till_retry = 300;
674   alarm(seconds_till_retry);
675   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 minutes"));
676 cp
677   return 0;
678 }
679
680 /*
681   close all open network connections
682 */
683 void close_network_connections(void)
684 {
685   conn_list_t *p;
686 cp
687   for(p = conn_list; p != NULL; p = p->next)
688     {
689       if(p->status.dataopen)
690         {
691           shutdown(p->socket, 0); /* No more receptions */
692           close(p->socket);
693         }
694       if(p->status.meta)
695         {
696           send_termreq(p);
697           shutdown(p->meta_socket, 0); /* No more receptions */
698           close(p->meta_socket);
699         }
700     }
701
702   if(myself)
703     if(myself->status.active)
704       {
705         close(myself->meta_socket);
706         close(myself->socket);
707       }
708
709   close(tap_fd);
710   destroy_conn_list();
711
712   syslog(LOG_NOTICE, _("Terminating"));
713 cp
714   return;
715 }
716
717 /*
718   create a data (udp) socket
719 */
720 int setup_vpn_connection(conn_list_t *cl)
721 {
722   int nfd, flags;
723   struct sockaddr_in a;
724 cp
725   if(debug_lvl > 0)
726     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
727
728   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
729   if(nfd == -1)
730     {
731       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
732       return -1;
733     }
734
735   a.sin_family = AF_INET;
736   a.sin_port = htons(cl->port);
737   a.sin_addr.s_addr = htonl(cl->real_ip);
738
739   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
740     {
741       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
742              cl->hostname, cl->port);
743       return -1;
744     }
745
746   flags = fcntl(nfd, F_GETFL);
747   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
748     {
749       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, nfd);
750       return -1;
751     }
752
753   cl->socket = nfd;
754   cl->status.dataopen = 1;
755 cp
756   return 0;
757 }
758
759 /*
760   handle an incoming tcp connect call and open
761   a connection to it.
762 */
763 conn_list_t *create_new_connection(int sfd)
764 {
765   conn_list_t *p;
766   struct sockaddr_in ci;
767   int len = sizeof(ci);
768 cp
769   p = new_conn_list();
770
771   if(getpeername(sfd, &ci, &len) < 0)
772     {
773       syslog(LOG_ERR, _("Error: getpeername: %m"));
774       return NULL;
775     }
776
777   p->real_ip = ntohl(ci.sin_addr.s_addr);
778   p->hostname = hostlookup(ci.sin_addr.s_addr);
779   p->meta_socket = sfd;
780   p->status.meta = 1;
781   p->buflen = 0;
782   p->last_ping_time = time(NULL);
783   p->want_ping = 0;
784   
785   if(debug_lvl > 0)
786     syslog(LOG_NOTICE, _("Connection from %s port %d"),
787          p->hostname, htons(ci.sin_port));
788
789   if(send_basic_info(p) < 0)
790     {
791       free(p);
792       return NULL;
793     }
794 cp
795   return p;
796 }
797
798 /*
799   put all file descriptors in an fd_set array
800 */
801 void build_fdset(fd_set *fs)
802 {
803   conn_list_t *p;
804 cp
805   FD_ZERO(fs);
806
807   for(p = conn_list; p != NULL; p = p->next)
808     {
809       if(p->status.meta)
810         FD_SET(p->meta_socket, fs);
811       if(p->status.dataopen)
812         FD_SET(p->socket, fs);
813     }
814
815   FD_SET(myself->meta_socket, fs);
816   FD_SET(myself->socket, fs);
817   FD_SET(tap_fd, fs);
818 cp
819 }
820
821 /*
822   receive incoming data from the listening
823   udp socket and write it to the ethertap
824   device after being decrypted
825 */
826 int handle_incoming_vpn_data(conn_list_t *cl)
827 {
828   real_packet_t rp;
829   int lenin;
830   int x, l = sizeof(x);
831   conn_list_t *f;
832 cp
833   if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
834     {
835       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, cl->socket);
836       return -1;
837     }
838   if(x)
839     {
840       syslog(LOG_ERR, _("Incoming data socket error: %s"), sys_errlist[x]);
841       return -1;
842     }
843
844   rp.len = -1;
845   lenin = recvfrom(cl->socket, &rp, MTU, 0, NULL, NULL);
846   if(lenin <= 0)
847     {
848       syslog(LOG_ERR, _("Receiving packet from %s failed: %m"), cl->hostname);
849       return -1;
850     }
851   total_socket_in += lenin;
852
853   rp.data.len = ntohs(rp.data.len);
854   rp.len = ntohs(rp.len);
855   rp.from = ntohl(rp.from);
856
857   if(rp.len >= 0)
858     {
859       f = lookup_conn(rp.from);
860       if(!f)
861         {
862           syslog(LOG_ERR, _("Got packet from " IP_ADDR_S " (%s) with unknown origin " IP_ADDR_S "?"),
863                  IP_ADDR_V(cl->vpn_ip), cl->hostname, IP_ADDR_V(rp.from));
864           return -1;
865         }
866
867       if(f->status.validkey)
868         xrecv(f, &rp);
869       else
870         {
871           add_queue(&(f->rq), &rp, rp.len);
872           if(!cl->status.waitingforkey)
873             send_key_request(rp.from);
874         }
875
876       if(my_key_expiry <= time(NULL))
877         regenerate_keys();
878     }
879 cp
880   return 0;
881 }
882
883 /*
884   terminate a connection and notify the other
885   end before closing the sockets
886 */
887 void terminate_connection(conn_list_t *cl)
888 {
889   conn_list_t *p, *q;
890
891 cp
892   if(cl->status.remove)
893     return;
894
895   if(debug_lvl > 0)
896     syslog(LOG_NOTICE, _("Closing connection with " IP_ADDR_S " (%s)"),
897            IP_ADDR_V(cl->vpn_ip), cl->hostname);
898
899   if(cl->status.timeout)
900     send_timeout(cl);
901   else if(!cl->status.termreq)
902     send_termreq(cl);
903
904   close(cl->socket);
905   if(cl->status.meta)
906     close(cl->meta_socket);
907
908   if(cl->status.outgoing)
909     {
910       signal(SIGALRM, sigalrm_handler);
911       seconds_till_retry = 5;
912       alarm(seconds_till_retry);
913       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
914     }
915   
916   cl->status.remove = 1;
917
918   /* If this cl isn't active, don't send any DEL_HOSTs and don't bother
919      checking for other lost connections. */
920   if(!cl->status.active)
921     return;
922     
923   cl->status.active = 0;
924
925 cp
926   /* Find all connections that were lost because they were behind cl
927      (the connection that was dropped). */
928   for(p = conn_list; p != NULL; p = p->next)
929     if(p->nexthop == cl)
930       {
931         p->status.active = 0;
932         p->status.remove = 1;
933       }
934
935 cp 
936   /* Then send a notification about all these connections to all hosts
937      that are still connected to us. */
938   for(p = conn_list; p != NULL; p = p->next)
939     if(!p->status.remove && p->status.meta)
940       for(q = conn_list; q != NULL; q = q->next)
941         if(q->status.remove)
942           send_del_host(p, q);
943
944 cp
945 }
946
947 /*
948   Check if the other end is active.
949   If we have sent packets, but didn't receive any,
950   then possibly the other end is dead. We send a
951   PING request over the meta connection. If the other
952   end does not reply in time, we consider them dead
953   and close the connection.
954 */
955 int check_dead_connections(void)
956 {
957   conn_list_t *p;
958   time_t now;
959 cp
960   now = time(NULL);
961   for(p = conn_list; p != NULL; p = p->next)
962     {
963       if(p->status.remove)
964         continue;
965       if(p->status.active && p->status.meta)
966         {
967           if(p->last_ping_time + timeout < now)
968             {
969               if(p->status.pinged && !p->status.got_pong)
970                 {
971                   if(debug_lvl > 1)
972                     syslog(LOG_INFO, _(IP_ADDR_S " (%s) didn't respond to ping"),
973                            IP_ADDR_V(p->vpn_ip), p->hostname);
974                   p->status.timeout = 1;
975                   terminate_connection(p);
976                 }
977               else if(p->want_ping)
978                 {
979                   send_ping(p);
980                   p->last_ping_time = now;
981                   p->status.pinged = 1;
982                   p->status.got_pong = 0;
983                 }
984             }
985         }
986     }
987 cp
988   return 0;
989 }
990
991 /*
992   accept a new tcp connect and create a
993   new connection
994 */
995 int handle_new_meta_connection(conn_list_t *cl)
996 {
997   conn_list_t *ncn;
998   struct sockaddr client;
999   int nfd, len = sizeof(client);
1000 cp
1001   if((nfd = accept(cl->meta_socket, &client, &len)) < 0)
1002     {
1003       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1004       return -1;
1005     }
1006
1007   if((ncn = create_new_connection(nfd)) == NULL)
1008     {
1009       shutdown(nfd, 2);
1010       close(nfd);
1011       syslog(LOG_NOTICE, _("Closed attempted connection"));
1012       return 0;
1013     }
1014
1015   ncn->status.meta = 1;
1016   ncn->next = conn_list;
1017   conn_list = ncn;
1018 cp
1019   return 0;
1020 }
1021
1022 /*
1023   dispatch any incoming meta requests
1024 */
1025 int handle_incoming_meta_data(conn_list_t *cl)
1026 {
1027   int x, l = sizeof(x);
1028   int request, oldlen, i;
1029   int lenin = 0;
1030 cp
1031   if(getsockopt(cl->meta_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1032     {
1033       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, cl->meta_socket);
1034       return -1;
1035     }
1036   if(x)
1037     {
1038       syslog(LOG_ERR, _("Metadata socket error: %s"), sys_errlist[x]);
1039       return -1;
1040     }
1041
1042   if(cl->buflen >= MAXBUFSIZE)
1043     {
1044       syslog(LOG_ERR, _("Metadata read buffer overflow!"));
1045       return -1;
1046     }
1047
1048   lenin = read(cl->meta_socket, cl->buffer, MAXBUFSIZE-cl->buflen);
1049
1050   if(lenin<=0)
1051     {
1052       syslog(LOG_ERR, _("Metadata socket read error: %m"));
1053       return -1;
1054     }
1055
1056   oldlen = cl->buflen;
1057   cl->buflen += lenin;
1058
1059   for(;;)
1060     {
1061       cl->reqlen = 0;
1062
1063       for(i = oldlen; i < cl->buflen; i++)
1064         {
1065           if(cl->buffer[i] == '\n')
1066             {
1067               cl->buffer[i] = 0;  /* replace end-of-line by end-of-string so we can use sscanf */
1068               cl->reqlen = i + 1;
1069               break;
1070             }
1071         }
1072
1073       if(cl->reqlen)
1074         {
1075           if(debug_lvl > 2)
1076             syslog(LOG_DEBUG, _("Got request from " IP_ADDR_S " (%s): %s"),
1077                          IP_ADDR_V(cl->vpn_ip), cl->hostname, cl->buffer);
1078           if(sscanf(cl->buffer, "%d", &request) == 1)
1079             {
1080               if((request < 0) || (request > 255) || (request_handlers[request] == NULL))
1081                 {
1082                   syslog(LOG_ERR, _("Unknown request from " IP_ADDR_S " (%s)"),
1083                          IP_ADDR_V(cl->vpn_ip), cl->hostname);
1084                   return -1;
1085                 }
1086
1087               if(request_handlers[request](cl))  /* Something went wrong. Probably scriptkiddies. Terminate. */
1088                 {
1089                   syslog(LOG_ERR, _("Error while processing request from " IP_ADDR_S " (%s)"),
1090                          IP_ADDR_V(cl->vpn_ip), cl->hostname);
1091                   return -1;
1092                 }
1093             }
1094           else
1095             {
1096               syslog(LOG_ERR, _("Bogus data received from " IP_ADDR_S " (%s)"),
1097                          IP_ADDR_V(cl->vpn_ip), cl->hostname);
1098               return -1;
1099             }
1100
1101           cl->buflen -= cl->reqlen;
1102           memmove(cl->buffer, cl->buffer + cl->reqlen, cl->buflen);
1103           oldlen = 0;
1104         }
1105       else
1106         {
1107           break;
1108         }
1109     }
1110
1111   cl->last_ping_time = time(NULL);
1112   cl->want_ping = 0;
1113 cp  
1114   return 0;
1115 }
1116
1117 /*
1118   check all connections to see if anything
1119   happened on their sockets
1120 */
1121 void check_network_activity(fd_set *f)
1122 {
1123   conn_list_t *p;
1124   int x, l = sizeof(x);
1125 cp
1126   for(p = conn_list; p != NULL; p = p->next)
1127     {
1128       if(p->status.remove)
1129         continue;
1130
1131       if(p->status.dataopen)
1132         if(FD_ISSET(p->socket, f))
1133           {
1134             /*
1135               The only thing that can happen to get us here is apparently an
1136               error on this outgoing(!) UDP socket that isn't immediate (i.e.
1137               something that will not trigger an error directly on send()).
1138               I've once got here when it said `No route to host'.
1139             */
1140             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1141             syslog(LOG_ERR, _("Outgoing data socket error: %s"), sys_errlist[x]);
1142             terminate_connection(p);
1143             return;
1144           }  
1145
1146       if(p->status.meta)
1147         if(FD_ISSET(p->meta_socket, f))
1148           if(handle_incoming_meta_data(p) < 0)
1149             {
1150               terminate_connection(p);
1151               return;
1152             } 
1153     }
1154   
1155   if(FD_ISSET(myself->socket, f))
1156     handle_incoming_vpn_data(myself);
1157
1158   if(FD_ISSET(myself->meta_socket, f))
1159     handle_new_meta_connection(myself);
1160 cp
1161 }
1162
1163 /*
1164   read, encrypt and send data that is
1165   available through the ethertap device
1166 */
1167 void handle_tap_input(void)
1168 {
1169   vpn_packet_t vp;
1170   ip_t from, to;
1171   int ether_type, lenin;
1172 cp  
1173   memset(&vp, 0, sizeof(vp));
1174   if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1175     {
1176       syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1177       return;
1178     }
1179
1180   total_tap_in += lenin;
1181
1182   ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1183   if(ether_type != 0x0800)
1184     {
1185       if(debug_lvl > 3)
1186         syslog(LOG_INFO, _("Non-IP ethernet frame %04x from " MAC_ADDR_S),
1187                ether_type, MAC_ADDR_V(vp.data[6]));
1188       return;
1189     }
1190   
1191   if(lenin < 32)
1192     {
1193       if(debug_lvl > 3)
1194         syslog(LOG_INFO, _("Dropping short packet"));
1195       return;
1196     }
1197
1198   from = ntohl(*((unsigned long*)(&vp.data[26])));
1199   to = ntohl(*((unsigned long*)(&vp.data[30])));
1200
1201   vp.len = (length_t)lenin - 2;
1202
1203   strip_mac_addresses(&vp);
1204
1205   send_packet(to, &vp);
1206 cp
1207 }
1208
1209 /*
1210   this is where it all happens...
1211 */
1212 void main_loop(void)
1213 {
1214   fd_set fset;
1215   struct timeval tv;
1216   int r;
1217   time_t last_ping_check;
1218 cp
1219   last_ping_check = time(NULL);
1220
1221   for(;;)
1222     {
1223       tv.tv_sec = timeout;
1224       tv.tv_usec = 0;
1225
1226       prune_conn_list();
1227       build_fdset(&fset);
1228
1229       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1230         {
1231           if(errno == EINTR) /* because of alarm */
1232             continue;
1233           syslog(LOG_ERR, _("Error while waiting for input: %m"));
1234           return;
1235         }
1236
1237       if(last_ping_check + timeout < time(NULL))
1238         /* Let's check if everybody is still alive */
1239         {
1240           check_dead_connections();
1241           last_ping_check = time(NULL);
1242           continue;
1243         }
1244
1245       check_network_activity(&fset);
1246
1247       /* local tap data */
1248       if(FD_ISSET(tap_fd, &fset))
1249         handle_tap_input();
1250     }
1251 cp
1252 }