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