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