- Fixing-things pass: every source file compiles into an object file now,
[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.34 2000/10/11 22:00: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 <utils.h>
41 #include <xalloc.h>
42
43 #include "conf.h"
44 #include "encr.h"
45 #include "net.h"
46 #include "netutl.h"
47 #include "protocol.h"
48 #include "meta.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 cp
72   memmove(p->data, p->data + 12, p->len -= 12);
73 cp
74 }
75
76 /*
77   reassemble MAC addresses
78 */
79 void add_mac_addresses(vpn_packet_t *p)
80 {
81 cp
82   memcpy(p->data + 12, p->data, p->len);
83   p->len += 12;
84   p->data[0] = p->data[6] = 0xfe;
85   p->data[1] = p->data[7] = 0xfd;
86   /* Really evil pointer stuff just below! */
87   *((ip_t*)(&p->data[2])) = (ip_t)(htonl(myself->address));
88   *((ip_t*)(&p->data[8])) = *((ip_t*)(&p->data[26]));
89 cp
90 }
91
92 int xsend(conn_list_t *cl, vpn_packet_t *inpkt)
93 {
94   vpn_packet_t outpkt;
95   int outlen, outpad;
96 cp
97   outpkt.len = inpkt->len;
98   EVP_EncryptInit(cl->cipher_pktctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktiv);
99   EVP_EncryptUpdate(cl->cipher_pktctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
100   EVP_EncryptFinal(cl->cipher_pktctx, outpkt.data + outlen, &outpad);
101   outlen += outpad;
102   
103   if(debug_lvl > 3)
104     syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
105            outlen, cl->name, cl->hostname);
106
107   total_socket_out += outlen;
108
109   cl->want_ping = 1;
110
111   if((send(cl->socket, (char *) &(outpkt.len), outlen + 2, 0)) < 0)
112     {
113       syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
114              cl->name, cl->hostname);
115       return -1;
116     }
117 cp
118   return 0;
119 }
120
121 int xrecv(vpn_packet_t *inpkt)
122 {
123   vpn_packet_t outpkt;
124   int outlen, outpad;
125 cp
126   if(debug_lvl > 3)
127     syslog(LOG_ERR, _("Receiving packet of %d bytes"),
128            inpkt->len);
129
130   outpkt.len = inpkt->len;
131   EVP_DecryptInit(myself->cipher_pktctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktiv);
132   EVP_DecryptUpdate(myself->cipher_pktctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
133   /* FIXME: grok DecryptFinal  
134   EVP_DecryptFinal(myself->cipher_pktctx, outpkt.data + outlen, &outpad);
135    */
136    
137   add_mac_addresses(&outpkt);
138
139   if(write(tap_fd, outpkt.data, outpkt.len) < 0)
140     syslog(LOG_ERR, _("Can't write to tap device: %m"));
141   else
142     total_tap_out += outpkt.len;
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->name, cl->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->name, cl->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_list_ipv4(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       return -1;
286    }
287     
288   /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
289
290   /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
291   
292   if(my_key_expiry <= time(NULL))
293     regenerate_keys();
294
295   if(!cl->status.dataopen)
296     if(setup_vpn_connection(cl) < 0)
297       {
298         syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
299                cl->name, cl->hostname);
300         return -1;
301       }
302       
303   if(!cl->status.validkey)
304     {
305       if(debug_lvl > 3)
306         syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
307                cl->name, cl->hostname);
308       add_queue(&(cl->sq), packet, packet->len + 2);
309       if(!cl->status.waitingforkey)
310         send_req_key(myself, cl);                       /* Keys should be sent to the host running the tincd */
311       return 0;
312     }
313
314   if(!cl->status.active)
315     {
316       if(debug_lvl > 3)
317         syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
318                cl->name, cl->hostname);
319       add_queue(&(cl->sq), packet, packet->len + 2);
320       return 0; /* We don't want to mess up, do we? */
321     }
322
323   /* can we send it? can we? can we? huh? */
324 cp
325   return xsend(cl, packet);
326 }
327
328 /*
329   open the local ethertap device
330 */
331 int setup_tap_fd(void)
332 {
333   int nfd;
334   const char *tapfname;
335   config_t const *cfg;
336 cp  
337   if((cfg = get_config_val(config, tapdevice)) == NULL)
338     tapfname = "/dev/tap0";
339   else
340     tapfname = cfg->data.ptr;
341
342   if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
343     {
344       syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
345       return -1;
346     }
347
348   tap_fd = nfd;
349 cp
350   return 0;
351 }
352
353 /*
354   set up the socket that we listen on for incoming
355   (tcp) connections
356 */
357 int setup_listen_meta_socket(int port)
358 {
359   int nfd, flags;
360   struct sockaddr_in a;
361   const int one = 1;
362   config_t const *cfg;
363 cp
364   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
365     {
366       syslog(LOG_ERR, _("Creating metasocket failed: %m"));
367       return -1;
368     }
369
370   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
371     {
372       syslog(LOG_ERR, _("setsockopt: %m"));
373       return -1;
374     }
375
376   if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
377     {
378       syslog(LOG_ERR, _("setsockopt: %m"));
379       return -1;
380     }
381
382   flags = fcntl(nfd, F_GETFL);
383   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
384     {
385       syslog(LOG_ERR, _("fcntl: %m"));
386       return -1;
387     }
388
389   if((cfg = get_config_val(config, interface)))
390     {
391       if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
392         {
393           syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
394           return -1;
395         }
396     }
397
398   memset(&a, 0, sizeof(a));
399   a.sin_family = AF_INET;
400   a.sin_port = htons(port);
401   
402   if((cfg = get_config_val(config, interfaceip)))
403     a.sin_addr.s_addr = htonl(cfg->data.ip->ip);
404   else
405     a.sin_addr.s_addr = htonl(INADDR_ANY);
406
407   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
408     {
409       syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
410       return -1;
411     }
412
413   if(listen(nfd, 3))
414     {
415       syslog(LOG_ERR, _("listen: %m"));
416       return -1;
417     }
418 cp
419   return nfd;
420 }
421
422 /*
423   setup the socket for incoming encrypted
424   data (the udp part)
425 */
426 int setup_vpn_in_socket(int port)
427 {
428   int nfd, flags;
429   struct sockaddr_in a;
430   const int one = 1;
431 cp
432   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
433     {
434       syslog(LOG_ERR, _("Creating socket failed: %m"));
435       return -1;
436     }
437
438   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
439     {
440       syslog(LOG_ERR, _("setsockopt: %m"));
441       return -1;
442     }
443
444   flags = fcntl(nfd, F_GETFL);
445   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
446     {
447       syslog(LOG_ERR, _("fcntl: %m"));
448       return -1;
449     }
450
451   memset(&a, 0, sizeof(a));
452   a.sin_family = AF_INET;
453   a.sin_port = htons(port);
454   a.sin_addr.s_addr = htonl(INADDR_ANY);
455
456   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
457     {
458       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
459       return -1;
460     }
461 cp
462   return nfd;
463 }
464
465 /*
466   setup an outgoing meta (tcp) socket
467 */
468 int setup_outgoing_meta_socket(conn_list_t *cl)
469 {
470   int flags;
471   struct sockaddr_in a;
472   config_t const *cfg;
473 cp
474   if(debug_lvl > 0)
475     syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
476
477   if((cfg = get_config_val(cl->config, port)) == NULL)
478     cl->port = 655;
479   else
480     cl->port = cfg->data.val;
481
482   cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
483   if(cl->meta_socket == -1)
484     {
485       syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
486              cl->hostname, cl->port);
487       return -1;
488     }
489
490   a.sin_family = AF_INET;
491   a.sin_port = htons(cl->port);
492   a.sin_addr.s_addr = htonl(cl->address);
493
494   if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
495     {
496       syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
497       return -1;
498     }
499
500   flags = fcntl(cl->meta_socket, F_GETFL);
501   if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
502     {
503       syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
504              cl->hostname, cl->port);
505       return -1;
506     }
507
508   if(debug_lvl > 0)
509     syslog(LOG_INFO, _("Connected to %s port %hd"),
510          cl->hostname, cl->port);
511 cp
512   return 0;
513 }
514
515 /*
516   setup an outgoing connection. It's not
517   necessary to also open an udp socket as
518   well, because the other host will initiate
519   an authentication sequence during which
520   we will do just that.
521 */
522 int setup_outgoing_connection(char *hostname)
523 {
524   conn_list_t *ncn;
525   struct hostent *h;
526 cp
527   if(!(h = gethostbyname(hostname)))
528     {
529       syslog(LOG_ERR, _("Error looking up `%s': %m"), hostname);
530       return -1;
531     }
532
533   ncn = new_conn_list();
534   ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
535   ncn->hostname = hostlookup(htonl(ncn->address));
536   
537   if(setup_outgoing_meta_socket(ncn) < 0)
538     {
539       syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
540              ncn->hostname);
541       free_conn_element(ncn);
542       return -1;
543     }
544
545   ncn->status.meta = 1;
546   ncn->status.outgoing = 1;
547   ncn->next = conn_list;
548   conn_list = ncn;
549 cp
550   return 0;
551 }
552
553 /*
554   set up the local sockets (listen only)
555 */
556 int setup_myself(void)
557 {
558   config_t const *cfg;
559 cp
560   myself = new_conn_list();
561
562   myself->hostname = "MYSELF"; /* FIXME? */
563   myself->flags = 0;
564
565   if(!(cfg = get_config_val(config, tincname))) /* Not acceptable */
566     {
567       syslog(LOG_ERR, _("Name for tinc daemon required!"));
568       return -1;
569     }
570   else
571     myself->name = (char*)cfg->data.val;
572   
573   if(!(cfg = get_config_val(myself, port)))
574     myself->port = 655;
575   else
576     myself->port = cfg->data.val;
577
578   if((cfg = get_config_val(config, indirectdata)))
579     if(cfg->data.val == stupid_true)
580       myself->flags |= EXPORTINDIRECTDATA;
581
582   if((cfg = get_config_val(config, tcponly)))
583     if(cfg->data.val == stupid_true)
584       myself->flags |= TCPONLY;
585
586   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
587     {
588       syslog(LOG_ERR, _("Unable to set up a listening socket"));
589       return -1;
590     }
591
592   if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
593     {
594       syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket"));
595       close(myself->meta_socket);
596       return -1;
597     }
598
599   myself->status.active = 1;
600
601   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
602 cp
603   return 0;
604 }
605
606 RETSIGTYPE
607 sigalrm_handler(int a)
608 {
609   config_t const *cfg;
610 cp
611 /* FIXME! Use name instead of upstreamip.
612   cfg = get_next_config_val(config, upstreamip, upstreamindex++);
613 */
614   while(cfg)
615     {
616       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
617         {
618           signal(SIGALRM, SIG_IGN);
619           return;
620         }
621 //      cfg = get_next_config_val(config, upstreamip, upstreamindex++); /* Or else we try the next ConnectTo line */
622     }
623
624   signal(SIGALRM, sigalrm_handler);
625   upstreamindex = 0;
626   seconds_till_retry += 5;
627   if(seconds_till_retry > MAXTIMEOUT)    /* Don't wait more than MAXTIMEOUT seconds. */
628     seconds_till_retry = MAXTIMEOUT;
629   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
630          seconds_till_retry);
631   alarm(seconds_till_retry);
632 cp
633 }
634
635 /*
636   setup all initial network connections
637 */
638 int setup_network_connections(void)
639 {
640   config_t const *cfg;
641 cp
642   if((cfg = get_config_val(config, pingtimeout)) == NULL)
643     timeout = 5;
644   else
645     timeout = cfg->data.val;
646
647   if(setup_tap_fd() < 0)
648     return -1;
649
650   if(setup_myself() < 0)
651     return -1;
652
653 //  if((cfg = get_next_config_val(config, upstreamip, upstreamindex++)) == NULL)
654     /* No upstream IP given, we're listen only. */
655     return 0;
656
657   while(cfg)
658     {
659       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
660         return 0;
661 //      cfg = get_next_config_val(config, upstreamip, upstreamindex++); /* Or else we try the next ConnectTo line */
662     }
663     
664   signal(SIGALRM, sigalrm_handler);
665   upstreamindex = 0;
666   seconds_till_retry = MAXTIMEOUT;
667   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
668   alarm(seconds_till_retry);
669 cp
670   return 0;
671 }
672
673 /*
674   close all open network connections
675 */
676 void close_network_connections(void)
677 {
678   conn_list_t *p;
679 cp
680   for(p = conn_list; p != NULL; p = p->next)
681     {
682       if(p->status.dataopen)
683         {
684           shutdown(p->socket, 0); /* No more receptions */
685           close(p->socket);
686         }
687       if(p->status.meta)
688         {
689           send_termreq(p);
690           shutdown(p->meta_socket, 0); /* No more receptions */
691           close(p->meta_socket);
692         }
693     }
694
695   if(myself)
696     if(myself->status.active)
697       {
698         close(myself->meta_socket);
699         close(myself->socket);
700       }
701
702   close(tap_fd);
703   destroy_conn_list();
704
705   syslog(LOG_NOTICE, _("Terminating"));
706 cp
707   return;
708 }
709
710 /*
711   create a data (udp) socket
712 */
713 int setup_vpn_connection(conn_list_t *cl)
714 {
715   int nfd, flags;
716   struct sockaddr_in a;
717 cp
718   if(debug_lvl > 0)
719     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
720
721   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
722   if(nfd == -1)
723     {
724       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
725       return -1;
726     }
727
728   a.sin_family = AF_INET;
729   a.sin_port = htons(cl->port);
730   a.sin_addr.s_addr = htonl(cl->address);
731
732   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
733     {
734       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
735              cl->hostname, cl->port);
736       return -1;
737     }
738
739   flags = fcntl(nfd, F_GETFL);
740   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
741     {
742       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
743              cl->name, cl->hostname);
744       return -1;
745     }
746
747   cl->socket = nfd;
748   cl->status.dataopen = 1;
749 cp
750   return 0;
751 }
752
753 /*
754   handle an incoming tcp connect call and open
755   a connection to it.
756 */
757 conn_list_t *create_new_connection(int sfd)
758 {
759   conn_list_t *p;
760   struct sockaddr_in ci;
761   int len = sizeof(ci);
762 cp
763   p = new_conn_list();
764
765   if(getpeername(sfd, &ci, &len) < 0)
766     {
767       syslog(LOG_ERR, _("Error: getpeername: %m"));
768       return NULL;
769     }
770
771   p->address = ntohl(ci.sin_addr.s_addr);
772   p->hostname = hostlookup(ci.sin_addr.s_addr);
773   p->meta_socket = sfd;
774   p->status.meta = 1;
775   p->buflen = 0;
776   p->last_ping_time = time(NULL);
777   p->want_ping = 0;
778   
779   if(debug_lvl > 0)
780     syslog(LOG_NOTICE, _("Connection from %s port %d"),
781          p->hostname, htons(ci.sin_port));
782
783   if(send_basic_info(p) < 0)
784     {
785       free_conn_element(p);
786       return NULL;
787     }
788 cp
789   return p;
790 }
791
792 /*
793   put all file descriptors in an fd_set array
794 */
795 void build_fdset(fd_set *fs)
796 {
797   conn_list_t *p;
798 cp
799   FD_ZERO(fs);
800
801   for(p = conn_list; p != NULL; p = p->next)
802     {
803       if(p->status.meta)
804         FD_SET(p->meta_socket, fs);
805       if(p->status.dataopen)
806         FD_SET(p->socket, fs);
807     }
808
809   FD_SET(myself->meta_socket, fs);
810   FD_SET(myself->socket, fs);
811   FD_SET(tap_fd, fs);
812 cp
813 }
814
815 /*
816   receive incoming data from the listening
817   udp socket and write it to the ethertap
818   device after being decrypted
819 */
820 int handle_incoming_vpn_data()
821 {
822   vpn_packet_t pkt;
823   int lenin;
824   int x, l = sizeof(x);
825 cp
826   if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
827     {
828       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
829              __FILE__, __LINE__, myself->socket);
830       return -1;
831     }
832   if(x)
833     {
834       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
835       return -1;
836     }
837
838   if(recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, NULL, NULL) <= 0)
839     {
840       syslog(LOG_ERR, _("Receiving packet failed: %m"));
841       return -1;
842     }
843
844 cp
845   return xrecv(&pkt);
846 }
847
848 /*
849   terminate a connection and notify the other
850   end before closing the sockets
851 */
852 void terminate_connection(conn_list_t *cl)
853 {
854   conn_list_t *p;
855
856 cp
857   if(cl->status.remove)
858     return;
859
860   if(debug_lvl > 0)
861     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
862            cl->name, cl->hostname);
863
864   if(cl->status.timeout)
865     send_timeout(cl);
866 /*  else if(!cl->status.termreq)
867     send_termreq(cl);
868  */
869  
870   if(cl->socket)
871     close(cl->socket);
872   if(cl->status.meta)
873     close(cl->meta_socket);
874
875   cl->status.remove = 1;
876
877   /* If this cl isn't active, don't send any DEL_HOSTs. */
878   if(cl->status.active)
879     notify_others(cl,NULL,send_del_host);
880     
881 cp
882   /* Find all connections that were lost because they were behind cl
883      (the connection that was dropped). */
884   if(cl->status.meta)
885     for(p = conn_list; p != NULL; p = p->next)
886       {
887         if((p->nexthop == cl) && (p != cl))
888           {
889             if(cl->status.active && p->status.active)
890               notify_others(p,cl,send_del_host);
891            if(cl->socket)
892              close(cl->socket);
893             p->status.active = 0;
894             p->status.remove = 1;
895           }
896       }
897     
898   cl->status.active = 0;
899   
900   if(cl->status.outgoing)
901     {
902       signal(SIGALRM, sigalrm_handler);
903       seconds_till_retry = 5;
904       alarm(seconds_till_retry);
905       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
906     }
907 cp
908 }
909
910 /*
911   Check if the other end is active.
912   If we have sent packets, but didn't receive any,
913   then possibly the other end is dead. We send a
914   PING request over the meta connection. If the other
915   end does not reply in time, we consider them dead
916   and close the connection.
917 */
918 int check_dead_connections(void)
919 {
920   conn_list_t *p;
921   time_t now;
922 cp
923   now = time(NULL);
924   for(p = conn_list; p != NULL; p = p->next)
925     {
926       if(p->status.remove)
927         continue;
928       if(p->status.active && p->status.meta)
929         {
930           if(p->last_ping_time + timeout < now)
931             {
932               if(p->status.pinged && !p->status.got_pong)
933                 {
934                   if(debug_lvl > 1)
935                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
936                            p->name, p->hostname);
937                   p->status.timeout = 1;
938                   terminate_connection(p);
939                 }
940               else if(p->want_ping)
941                 {
942                   send_ping(p);
943                   p->last_ping_time = now;
944                   p->status.pinged = 1;
945                   p->status.got_pong = 0;
946                 }
947             }
948         }
949     }
950 cp
951   return 0;
952 }
953
954 /*
955   accept a new tcp connect and create a
956   new connection
957 */
958 int handle_new_meta_connection()
959 {
960   conn_list_t *ncn;
961   struct sockaddr client;
962   int nfd, len = sizeof(client);
963 cp
964   if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
965     {
966       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
967       return -1;
968     }
969
970   if(!(ncn = create_new_connection(nfd)))
971     {
972       shutdown(nfd, 2);
973       close(nfd);
974       syslog(LOG_NOTICE, _("Closed attempted connection"));
975       return 0;
976     }
977
978   ncn->status.meta = 1;
979   ncn->next = conn_list;
980   conn_list = ncn;
981 cp
982   return 0;
983 }
984
985 /*
986   check all connections to see if anything
987   happened on their sockets
988 */
989 void check_network_activity(fd_set *f)
990 {
991   conn_list_t *p;
992   int x, l = sizeof(x);
993 cp
994   for(p = conn_list; p != NULL; p = p->next)
995     {
996       if(p->status.remove)
997         continue;
998
999       if(p->status.dataopen)
1000         if(FD_ISSET(p->socket, f))
1001           {
1002             /*
1003               The only thing that can happen to get us here is apparently an
1004               error on this outgoing(!) UDP socket that isn't immediate (i.e.
1005               something that will not trigger an error directly on send()).
1006               I've once got here when it said `No route to host'.
1007             */
1008             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1009             syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1010                    p->name, p->hostname, strerror(x));
1011             terminate_connection(p);
1012             return;
1013           }  
1014
1015       if(p->status.meta)
1016         if(FD_ISSET(p->meta_socket, f))
1017           if(receive_meta(p) < 0)
1018             {
1019               terminate_connection(p);
1020               return;
1021             } 
1022     }
1023   
1024   if(FD_ISSET(myself->socket, f))
1025     handle_incoming_vpn_data();
1026
1027   if(FD_ISSET(myself->meta_socket, f))
1028     handle_new_meta_connection();
1029 cp
1030 }
1031
1032 /*
1033   read, encrypt and send data that is
1034   available through the ethertap device
1035 */
1036 void handle_tap_input(void)
1037 {
1038   vpn_packet_t vp;
1039   ip_t from, to;
1040   int ether_type, lenin;
1041 cp  
1042   memset(&vp, 0, sizeof(vp));
1043   if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1044     {
1045       syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1046       return;
1047     }
1048
1049   total_tap_in += lenin;
1050
1051   ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1052   if(ether_type != 0x0800)
1053     {
1054       if(debug_lvl > 3)
1055         syslog(LOG_INFO, _("Non-IP ethernet frame %04x from %02x:%02x:%02x:%02x:%02x:%02x"), ether_type, MAC_ADDR_V(vp.data[6]));
1056       return;
1057     }
1058   
1059   if(lenin < 32)
1060     {
1061       if(debug_lvl > 3)
1062         syslog(LOG_INFO, _("Dropping short packet from %02x:%02x:%02x:%02x:%02x:%02x"), MAC_ADDR_V(vp.data[6]));
1063       return;
1064     }
1065
1066   from = ntohl(*((unsigned long*)(&vp.data[26])));
1067   to = ntohl(*((unsigned long*)(&vp.data[30])));
1068
1069   vp.len = (length_t)lenin - 2;
1070
1071   strip_mac_addresses(&vp);
1072
1073   send_packet(to, &vp);
1074 cp
1075 }
1076
1077 /*
1078   this is where it all happens...
1079 */
1080 void main_loop(void)
1081 {
1082   fd_set fset;
1083   struct timeval tv;
1084   int r;
1085   time_t last_ping_check;
1086 cp
1087   last_ping_check = time(NULL);
1088
1089   for(;;)
1090     {
1091       tv.tv_sec = timeout;
1092       tv.tv_usec = 0;
1093
1094       prune_conn_list();
1095       build_fdset(&fset);
1096
1097       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1098         {
1099           if(errno != EINTR) /* because of alarm */
1100             {
1101               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1102               return;
1103             }
1104         }
1105
1106       if(sighup)
1107         {
1108           sighup = 0;
1109           if(debug_lvl > 1)
1110             syslog(LOG_INFO, _("Rereading configuration file"));
1111           close_network_connections();
1112           clear_config();
1113           if(read_config_file(&config, configfilename))
1114             {
1115               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1116               exit(0);
1117             }
1118           sleep(5);
1119           setup_network_connections();
1120           continue;
1121         }
1122
1123       if(last_ping_check + timeout < time(NULL))
1124         /* Let's check if everybody is still alive */
1125         {
1126           check_dead_connections();
1127           last_ping_check = time(NULL);
1128         }
1129
1130       if(r > 0)
1131         {
1132           check_network_activity(&fset);
1133
1134           /* local tap data */
1135           if(FD_ISSET(tap_fd, &fset))
1136             handle_tap_input();
1137         }
1138     }
1139 cp
1140 }