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