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