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