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