Removed lots of compiler warnings.
[tinc] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998-2001 Ivo Timmermans <itimmermans@bigfoot.com>,
4                   2000,2001 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.100 2001/02/27 16:37:25 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <netdb.h>
28 #include <netinet/in.h>
29 #include <netinet/ip.h>
30 #include <netinet/tcp.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sys/signal.h>
35 #include <sys/time.h>
36 #include <sys/types.h>
37 #include <syslog.h>
38 #include <unistd.h>
39 #include <sys/ioctl.h>
40 /* SunOS really wants sys/socket.h BEFORE net/if.h,
41    and FreeBSD wants these lines below the rest. */
42 #include <arpa/inet.h>
43 #include <sys/socket.h>
44 #include <net/if.h>
45
46 #ifdef HAVE_OPENSSL_RAND_H
47 # include <openssl/rand.h>
48 #else
49 # include <rand.h>
50 #endif
51
52 #ifdef HAVE_OPENSSL_EVP_H
53 # include <openssl/evp.h>
54 #else
55 # include <evp.h>
56 #endif
57
58 #ifdef HAVE_OPENSSL_ERR_H
59 # include <openssl/err.h>
60 #else
61 # include <err.h>
62 #endif
63
64 #ifdef HAVE_OPENSSL_PEM_H
65 # include <openssl/pem.h>
66 #else
67 # include <pem.h>
68 #endif
69
70 #ifdef HAVE_TUNTAP
71 #include LINUX_IF_TUN_H
72 #endif
73
74 #include <utils.h>
75 #include <xalloc.h>
76 #include <avl_tree.h>
77 #include <list.h>
78
79 #include "conf.h"
80 #include "connection.h"
81 #include "meta.h"
82 #include "net.h"
83 #include "netutl.h"
84 #include "process.h"
85 #include "protocol.h"
86 #include "subnet.h"
87
88 #include "system.h"
89
90 int tap_fd = -1;
91 int taptype = TAP_TYPE_ETHERTAP;
92 int total_tap_in = 0;
93 int total_tap_out = 0;
94 int total_socket_in = 0;
95 int total_socket_out = 0;
96
97 config_t *upstreamcfg;
98 static int seconds_till_retry;
99
100 int keylifetime = 0;
101 int keyexpires = 0;
102
103 char *unknown = NULL;
104
105 subnet_t mymac;
106
107 int xsend(connection_t *cl, vpn_packet_t *inpkt)
108 {
109   vpn_packet_t outpkt;
110   int outlen, outpad;
111   EVP_CIPHER_CTX ctx;
112   struct sockaddr_in to;
113   socklen_t tolen = sizeof(to);
114 cp
115   outpkt.len = inpkt->len;
116   
117   /* Encrypt the packet. */
118   
119   EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
120   EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
121   EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
122   outlen += outpad + 2;
123
124 /* Bypass
125   outlen = outpkt.len + 2;
126   memcpy(&outpkt, inpkt, outlen);
127 */  
128
129   if(debug_lvl >= DEBUG_TRAFFIC)
130     syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
131            outlen, cl->name, cl->hostname);
132
133   total_socket_out += outlen;
134
135   to.sin_family = AF_INET;
136   to.sin_addr.s_addr = htonl(cl->address);
137   to.sin_port = htons(cl->port);
138
139   if((sendto(myself->socket, (char *) &(outpkt.len), outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
140     {
141       syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
142              cl->name, cl->hostname);
143       return -1;
144     }
145 cp
146   return 0;
147 }
148
149 int xrecv(connection_t *cl, vpn_packet_t *inpkt)
150 {
151   vpn_packet_t outpkt;
152   int outlen, outpad;
153   EVP_CIPHER_CTX ctx;
154 cp
155   outpkt.len = inpkt->len;
156
157   /* Decrypt the packet */
158
159   EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
160   EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
161   EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
162   outlen += outpad;
163
164 /* Bypass
165   outlen = outpkt.len+2;
166   memcpy(&outpkt, inpkt, outlen);
167 */
168 cp
169   return receive_packet(cl, &outpkt);
170 }
171
172 int receive_packet(connection_t *cl, vpn_packet_t *packet)
173 {
174   if(debug_lvl >= DEBUG_TRAFFIC)
175     syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
176            packet->len);
177
178   /* Fix mac address */
179
180   memcpy(packet->data, mymac.net.mac.address.x, 6);
181
182   if(taptype == TAP_TYPE_TUNTAP)
183     {
184       if(write(tap_fd, packet->data, packet->len) < 0)
185         syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
186       else
187         total_tap_out += packet->len;
188     }
189   else  /* ethertap */
190     {
191       if(write(tap_fd, packet->data - 2, packet->len + 2) < 0)
192         syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
193       else
194         total_tap_out += packet->len + 2;
195     }
196 cp
197   return 0;
198 }
199
200 /*
201   send a packet to the given vpn ip.
202 */
203 int send_packet(ip_t to, vpn_packet_t *packet)
204 {
205   connection_t *cl;
206   subnet_t *subnet;
207   vpn_packet_t *copy;
208 cp
209   if((subnet = lookup_subnet_ipv4(&to)) == NULL)
210     {
211       if(debug_lvl >= DEBUG_TRAFFIC)
212         {
213           syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
214                  IP_ADDR_V(to));
215         }
216
217       return -1;
218     }
219
220   cl = subnet->owner;
221     
222   if(cl == myself)
223     {
224       if(debug_lvl >= DEBUG_TRAFFIC)
225         {
226           syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
227                  IP_ADDR_V(to));
228         }
229
230       return -1;
231     }
232
233   if(!cl->status.active)
234     {
235       if(debug_lvl >= DEBUG_TRAFFIC)
236         syslog(LOG_INFO, _("%s (%s) is not active, dropping packet"),
237                cl->name, cl->hostname);
238
239       return 0;
240     }
241
242   if(!cl->status.validkey)
243     {
244       if(debug_lvl >= DEBUG_TRAFFIC)
245         syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
246                cl->name, cl->hostname);
247
248       /* Since packet is on the stack of handle_tap_input(),
249          we have to make a copy of it first. */
250
251       copy = xmalloc(sizeof(vpn_packet_t));
252       memcpy(copy, packet, sizeof(vpn_packet_t));
253
254       list_insert_tail(cl->queue, copy);
255
256       if(!cl->status.waitingforkey)
257         send_req_key(myself, cl);                       /* Keys should be sent to the host running the tincd */
258       return 0;
259     }
260
261   /* Check if it has to go via UDP or TCP... */
262 cp
263   if(cl->options & OPTION_TCPONLY)
264     return send_tcppacket(cl, packet);      
265   else
266     return xsend(cl, packet);
267 }
268
269 void flush_queue(connection_t *cl)
270 {
271   list_node_t *node, *next;
272 cp
273   if(debug_lvl >= DEBUG_TRAFFIC)
274     syslog(LOG_INFO, _("Flushing queue for %s (%s)"), cl->name, cl->hostname);
275   
276   for(node = cl->queue->head; node; node = next)
277     {
278       next = node->next;
279       xsend(cl, (vpn_packet_t *)node->data);
280       list_delete_node(cl->queue, node);
281     }
282 cp
283 }
284
285 /*
286   open the local ethertap device
287 */
288 int setup_tap_fd(void)
289 {
290   int nfd;
291   const char *tapfname;
292   config_t const *cfg;
293 #ifdef HAVE_LINUX
294 # ifdef HAVE_TUNTAP
295   struct ifreq ifr;
296 # endif
297 #endif
298
299 cp  
300   if((cfg = get_config_val(config, config_tapdevice)))
301     tapfname = cfg->data.ptr;
302   else
303    {
304 #ifdef HAVE_LINUX
305 # ifdef HAVE_TUNTAP
306       tapfname = "/dev/misc/net/tun";
307 # else
308       tapfname = "/dev/tap0";
309 # endif
310 #endif
311 #ifdef HAVE_FREEBSD
312       tapfname = "/dev/tap0";
313 #endif
314 #ifdef HAVE_SOLARIS
315       tapfname = "/dev/tun";
316 #endif
317    }
318 cp
319   if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
320     {
321       syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
322       return -1;
323     }
324 cp
325   tap_fd = nfd;
326
327   taptype = TAP_TYPE_ETHERTAP;
328
329   /* Set default MAC address for ethertap devices */
330   
331   mymac.type = SUBNET_MAC;
332   mymac.net.mac.address.x[0] = 0xfe;
333   mymac.net.mac.address.x[1] = 0xfd;
334   mymac.net.mac.address.x[2] = 0x00;
335   mymac.net.mac.address.x[3] = 0x00;
336   mymac.net.mac.address.x[4] = 0x00;
337   mymac.net.mac.address.x[5] = 0x00;
338
339 #ifdef HAVE_LINUX
340  #ifdef HAVE_TUNTAP
341   /* Ok now check if this is an old ethertap or a new tun/tap thingie */
342   memset(&ifr, 0, sizeof(ifr));
343 cp
344   ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
345   if (netname)
346     strncpy(ifr.ifr_name, netname, IFNAMSIZ);
347 cp
348   if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
349   {
350     syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
351     taptype = TAP_TYPE_TUNTAP;
352   }
353  #endif
354 #endif
355 #ifdef HAVE_FREEBSD
356  taptype = TAP_TYPE_TUNTAP;
357 #endif
358 cp
359   return 0;
360 }
361
362 /*
363   set up the socket that we listen on for incoming
364   (tcp) connections
365 */
366 int setup_listen_meta_socket(int port)
367 {
368   int nfd, flags;
369   struct sockaddr_in a;
370   int option;
371   config_t const *cfg;
372 cp
373   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
374     {
375       syslog(LOG_ERR, _("Creating metasocket failed: %m"));
376       return -1;
377     }
378
379   flags = fcntl(nfd, F_GETFL);
380   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
381     {
382       close(nfd);
383       syslog(LOG_ERR, _("System call `%s' failed: %m"),
384              "fcntl");
385       return -1;
386     }
387
388   /* Optimize TCP settings */
389   
390   option = 1;
391   setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
392   setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
393   setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
394
395   option = IPTOS_LOWDELAY;
396   setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
397   
398   if((cfg = get_config_val(config, config_interface)))
399     {
400       if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, cfg->data.ptr, strlen(cfg->data.ptr)))
401         {
402           close(nfd);
403           syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
404           return -1;
405         }
406     }
407
408   memset(&a, 0, sizeof(a));
409   a.sin_family = AF_INET;
410   a.sin_port = htons(port);
411   
412   if((cfg = get_config_val(config, config_interfaceip)))
413     a.sin_addr.s_addr = htonl(cfg->data.ip->address);
414   else
415     a.sin_addr.s_addr = htonl(INADDR_ANY);
416
417   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
418     {
419       close(nfd);
420       syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
421       return -1;
422     }
423
424   if(listen(nfd, 3))
425     {
426       close(nfd);
427       syslog(LOG_ERR, _("System call `%s' failed: %m"),
428              "listen");
429       return -1;
430     }
431 cp
432   return nfd;
433 }
434
435 /*
436   setup the socket for incoming encrypted
437   data (the udp part)
438 */
439 int setup_vpn_in_socket(int port)
440 {
441   int nfd, flags;
442   struct sockaddr_in a;
443   const int one = 1;
444 cp
445   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
446     {
447       close(nfd);
448       syslog(LOG_ERR, _("Creating socket failed: %m"));
449       return -1;
450     }
451
452   setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
453
454   flags = fcntl(nfd, F_GETFL);
455   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
456     {
457       close(nfd);
458       syslog(LOG_ERR, _("System call `%s' failed: %m"),
459              "fcntl");
460       return -1;
461     }
462
463   memset(&a, 0, sizeof(a));
464   a.sin_family = AF_INET;
465   a.sin_port = htons(port);
466   a.sin_addr.s_addr = htonl(INADDR_ANY);
467
468   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
469     {
470       close(nfd);
471       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
472       return -1;
473     }
474 cp
475   return nfd;
476 }
477
478 /*
479   setup an outgoing meta (tcp) socket
480 */
481 int setup_outgoing_meta_socket(connection_t *cl)
482 {
483   int flags;
484   struct sockaddr_in a;
485   config_t const *cfg;
486   int option;
487 cp
488   if(debug_lvl >= DEBUG_CONNECTIONS)
489     syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
490
491   if((cfg = get_config_val(cl->config, config_port)) == NULL)
492     cl->port = 655;
493   else
494     cl->port = cfg->data.val;
495
496   cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
497   if(cl->meta_socket == -1)
498     {
499       syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
500              cl->hostname, cl->port);
501       return -1;
502     }
503
504   /* Bind first to get a fix on our source port */
505
506   a.sin_family = AF_INET;
507   a.sin_port = htons(0);
508   a.sin_addr.s_addr = htonl(INADDR_ANY);
509
510   if(bind(cl->meta_socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
511     {
512       close(cl->meta_socket);
513       syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
514       return -1;
515     }
516
517   /* Optimize TCP settings */
518   
519   option = 1;
520   setsockopt(cl->meta_socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
521   setsockopt(cl->meta_socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
522
523   option = IPTOS_LOWDELAY;
524   setsockopt(cl->meta_socket, SOL_IP, IP_TOS, &option, sizeof(option));
525   
526   /* Connect */
527   
528   a.sin_family = AF_INET;
529   a.sin_port = htons(cl->port);
530   a.sin_addr.s_addr = htonl(cl->address);
531
532   if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
533     {
534       close(cl->meta_socket);
535       syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
536       return -1;
537     }
538
539   flags = fcntl(cl->meta_socket, F_GETFL);
540   if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
541     {
542       close(cl->meta_socket);
543       syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
544              cl->hostname, cl->port);
545       return -1;
546     }
547
548   if(debug_lvl >= DEBUG_CONNECTIONS)
549     syslog(LOG_INFO, _("Connected to %s port %hd"),
550          cl->hostname, cl->port);
551
552   cl->status.meta = 1;
553 cp
554   return 0;
555 }
556
557 /*
558   Setup an outgoing meta connection.
559 */
560 int setup_outgoing_connection(char *name)
561 {
562   connection_t *ncn;
563   struct hostent *h;
564   config_t const *cfg;
565 cp
566   if(check_id(name))
567     {
568       syslog(LOG_ERR, _("Invalid name for outgoing connection"));
569       return -1;
570     }
571
572   ncn = new_connection();
573   asprintf(&ncn->name, "%s", name);
574     
575   if(read_host_config(ncn))
576     {
577       syslog(LOG_ERR, _("Error reading host configuration file for %s"), ncn->name);
578       free_connection(ncn);
579       return -1;
580     }
581     
582   if(!(cfg = get_config_val(ncn->config, config_address)))
583     {
584       syslog(LOG_ERR, _("No address specified for %s"), ncn->name);
585       free_connection(ncn);
586       return -1;
587     }
588     
589   if(!(h = gethostbyname(cfg->data.ptr)))
590     {
591       syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
592       free_connection(ncn);
593       return -1;
594     }
595
596   ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
597   ncn->hostname = hostlookup(htonl(ncn->address));
598   
599   if(setup_outgoing_meta_socket(ncn) < 0)
600     {
601       syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
602              ncn->hostname);
603       free_connection(ncn);
604       return -1;
605     }
606
607   ncn->status.outgoing = 1;
608   ncn->buffer = xmalloc(MAXBUFSIZE);
609   ncn->buflen = 0;
610   ncn->last_ping_time = time(NULL);
611
612   connection_add(ncn);
613
614   send_id(ncn);
615 cp
616   return 0;
617 }
618
619 int read_rsa_public_key(connection_t *cl)
620 {
621   config_t const *cfg;
622   FILE *fp;
623   char *fname;
624   void *result;
625 cp
626   if(!cl->rsa_key)
627     cl->rsa_key = RSA_new();
628
629   /* First, check for simple PublicKey statement */
630
631   if((cfg = get_config_val(cl->config, config_publickey)))
632     {
633       BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
634       BN_hex2bn(&cl->rsa_key->e, "FFFF");
635       return 0;
636     }
637
638   /* Else, check for PublicKeyFile statement and read it */
639
640   if((cfg = get_config_val(cl->config, config_publickeyfile)))
641     {
642       if(is_safe_path(cfg->data.ptr))
643         {
644           if((fp = fopen(cfg->data.ptr, "r")) == NULL)
645             {
646               syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
647                      cfg->data.ptr);
648               return -1;
649             }
650           result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
651           fclose(fp);
652           if(!result)
653             {
654               syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
655                      cfg->data.ptr);
656               return -1;
657             }
658           return 0;
659         }
660       else
661         return -1;
662     }    
663
664   /* Else, check if a harnessed public key is in the config file */
665   
666   asprintf(&fname, "%s/hosts/%s", confbase, cl->name);
667   if((fp = fopen(fname, "r")))
668     {
669       result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
670       fclose(fp);
671       free(fname);
672       if(result)
673         return 0;
674     }
675
676   free(fname);
677
678   /* Nothing worked. */
679
680   syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
681 cp
682   return -1;
683 }
684
685 int read_rsa_private_key(void)
686 {
687   config_t const *cfg;
688   FILE *fp;
689   void *result;
690 cp
691   if(!myself->rsa_key)
692     myself->rsa_key = RSA_new();
693
694   if((cfg = get_config_val(config, config_privatekey)))
695     {
696       BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
697       BN_hex2bn(&myself->rsa_key->e, "FFFF");
698     }
699   else if((cfg = get_config_val(config, config_privatekeyfile)))
700     {
701       if((fp = fopen(cfg->data.ptr, "r")) == NULL)
702         {
703           syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
704                  cfg->data.ptr);
705           return -1;
706         }
707       result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
708       fclose(fp);
709       if(!result)
710         {
711           syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
712                  cfg->data.ptr);
713           return -1;
714         }
715     }    
716   else
717     {
718       syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
719       return -1;
720     }
721 cp
722   return 0;
723 }
724
725 /*
726   Configure connection_t myself and set up the local sockets (listen only)
727 */
728 int setup_myself(void)
729 {
730   config_t const *cfg;
731   config_t *next;
732   subnet_t *net;
733 cp
734   myself = new_connection();
735
736   asprintf(&myself->hostname, "MYSELF");
737   myself->flags = 0;
738   myself->protocol_version = PROT_CURRENT;
739
740   if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
741     {
742       syslog(LOG_ERR, _("Name for tinc daemon required!"));
743       return -1;
744     }
745   else
746     asprintf(&myself->name, "%s", (char*)cfg->data.val);
747
748   if(check_id(myself->name))
749     {
750       syslog(LOG_ERR, _("Invalid name for myself!"));
751       return -1;
752     }
753 cp
754   if(read_rsa_private_key())
755     return -1;
756
757   if(read_host_config(myself))
758     {
759       syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
760       return -1;
761     }
762
763   if(read_rsa_public_key(myself))
764     return -1;
765 cp  
766
767 /*
768   if(RSA_check_key(myself->rsa_key) != 1)
769     {
770       syslog(LOG_ERR, _("Invalid public/private keypair!"));
771       return -1;
772     }
773 */
774   if(!(cfg = get_config_val(myself->config, config_port)))
775     myself->port = 655;
776   else
777     myself->port = cfg->data.val;
778
779   if((cfg = get_config_val(myself->config, config_indirectdata)))
780     if(cfg->data.val == stupid_true)
781       myself->flags |= EXPORTINDIRECTDATA;
782
783   if((cfg = get_config_val(myself->config, config_tcponly)))
784     if(cfg->data.val == stupid_true)
785       myself->flags |= TCPONLY;
786
787 /* Read in all the subnets specified in the host configuration file */
788
789   for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
790     {
791       net = new_subnet();
792       net->type = SUBNET_IPV4;
793       net->net.ipv4.address = cfg->data.ip->address;
794       net->net.ipv4.mask = cfg->data.ip->mask;
795       
796       /* Teach newbies what subnets are... */
797       
798       if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
799         {
800           syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
801           return -1;
802         }        
803       
804       subnet_add(myself, net);
805     }
806     
807   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
808     {
809       syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
810       return -1;
811     }
812
813   if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
814     {
815       syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
816       return -1;
817     }
818 cp
819   /* Generate packet encryption key */
820
821   myself->cipher_pkttype = EVP_bf_cbc();
822
823   myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
824
825   myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
826   RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
827
828   if(!(cfg = get_config_val(config, config_keyexpire)))
829     keylifetime = 3600;
830   else
831     keylifetime = cfg->data.val;
832     
833   keyexpires = time(NULL) + keylifetime;
834 cp
835   /* Check some options */
836   
837   if((cfg = get_config_val(config, config_indirectdata)))
838     {
839       if(cfg->data.val == stupid_true)
840         myself->options |= OPTION_INDIRECT;
841     }
842
843   if((cfg = get_config_val(config, config_tcponly)))
844     {
845       if(cfg->data.val == stupid_true)
846         myself->options |= OPTION_TCPONLY;
847     }
848   /* Activate ourselves */
849
850   myself->status.active = 1;
851
852   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
853 cp
854   return 0;
855 }
856
857 RETSIGTYPE
858 sigalrm_handler(int a)
859 {
860   config_t const *cfg;
861 cp
862   cfg = get_config_val(upstreamcfg, config_connectto);
863
864   if(!cfg && upstreamcfg == config)
865     /* No upstream IP given, we're listen only. */
866     return;
867
868   while(cfg)
869     {
870       upstreamcfg = cfg->next;
871       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
872         {
873           signal(SIGALRM, SIG_IGN);
874           return;
875         }
876       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
877     }
878
879   signal(SIGALRM, sigalrm_handler);
880   upstreamcfg = config;
881   seconds_till_retry += 5;
882   if(seconds_till_retry > MAXTIMEOUT)    /* Don't wait more than MAXTIMEOUT seconds. */
883     seconds_till_retry = MAXTIMEOUT;
884   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
885          seconds_till_retry);
886   alarm(seconds_till_retry);
887 cp
888 }
889
890 /*
891   setup all initial network connections
892 */
893 int setup_network_connections(void)
894 {
895   config_t const *cfg;
896 cp
897   init_connections();
898   init_subnets();
899
900   if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
901     timeout = 60;
902   else
903     {
904       timeout = cfg->data.val;
905       if(timeout < 1)
906         {
907           timeout = 86400;
908         }
909      }
910
911   if(setup_tap_fd() < 0)
912     return -1;
913
914   /* Run tinc-up script to further initialize the tap interface */
915   execute_script("tinc-up");
916   
917   if(setup_myself() < 0)
918     return -1;
919
920   if(!(cfg = get_config_val(config, config_connectto)))
921     /* No upstream IP given, we're listen only. */
922     return 0;
923
924   while(cfg)
925     {
926       upstreamcfg = cfg->next;
927       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
928         return 0;
929       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
930     }
931     
932   signal(SIGALRM, sigalrm_handler);
933   upstreamcfg = config;
934   seconds_till_retry = MAXTIMEOUT;
935   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
936   alarm(seconds_till_retry);
937 cp
938   return 0;
939 }
940
941 /*
942   close all open network connections
943 */
944 void close_network_connections(void)
945 {
946   avl_node_t *node;
947   connection_t *p;
948 cp
949   for(node = connection_tree->head; node; node = node->next)
950     {
951       p = (connection_t *)node->data;
952       p->status.active = 0;
953       terminate_connection(p);
954     }
955
956   if(myself)
957     if(myself->status.active)
958       {
959         close(myself->meta_socket);
960         free_connection(myself);
961         myself = NULL;
962       }
963
964   close(tap_fd);
965
966   /* Execute tinc-down script right after shutting down the interface */
967   execute_script("tinc-down");
968
969   destroy_connection_tree();
970 cp
971   return;
972 }
973
974 /*
975   handle an incoming tcp connect call and open
976   a connection to it.
977 */
978 connection_t *create_new_connection(int sfd)
979 {
980   connection_t *p;
981   struct sockaddr_in ci;
982   int len = sizeof(ci);
983 cp
984   p = new_connection();
985
986   if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
987     {
988       syslog(LOG_ERR, _("System call `%s' failed: %m"),
989              "getpeername");
990       close(sfd);
991       return NULL;
992     }
993
994   p->name = unknown;
995   p->address = ntohl(ci.sin_addr.s_addr);
996   p->hostname = hostlookup(ci.sin_addr.s_addr);
997   p->port = htons(ci.sin_port);                         /* This one will be overwritten later */
998   p->meta_socket = sfd;
999   p->status.meta = 1;
1000   p->buffer = xmalloc(MAXBUFSIZE);
1001   p->buflen = 0;
1002   p->last_ping_time = time(NULL);
1003   
1004   if(debug_lvl >= DEBUG_CONNECTIONS)
1005     syslog(LOG_NOTICE, _("Connection from %s port %d"),
1006          p->hostname, htons(ci.sin_port));
1007
1008   p->allow_request = ID;
1009 cp
1010   return p;
1011 }
1012
1013 /*
1014   put all file descriptors in an fd_set array
1015 */
1016 void build_fdset(fd_set *fs)
1017 {
1018   avl_node_t *node;
1019   connection_t *p;
1020 cp
1021   FD_ZERO(fs);
1022
1023   FD_SET(myself->socket, fs);
1024
1025   for(node = connection_tree->head; node; node = node->next)
1026     {
1027       p = (connection_t *)node->data;
1028       if(p->status.meta)
1029         FD_SET(p->meta_socket, fs);
1030     }
1031
1032   FD_SET(myself->meta_socket, fs);
1033   FD_SET(tap_fd, fs);
1034 cp
1035 }
1036
1037 /*
1038   receive incoming data from the listening
1039   udp socket and write it to the ethertap
1040   device after being decrypted
1041 */
1042 int handle_incoming_vpn_data(void)
1043 {
1044   vpn_packet_t pkt;
1045   int x, l = sizeof(x);
1046   int lenin;
1047   struct sockaddr_in from;
1048   socklen_t fromlen = sizeof(from);
1049   connection_t *cl;
1050 cp
1051   if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1052     {
1053       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1054              __FILE__, __LINE__, myself->socket);
1055       return -1;
1056     }
1057   if(x)
1058     {
1059       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1060       return -1;
1061     }
1062
1063   if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1064     {
1065       syslog(LOG_ERR, _("Receiving packet failed: %m"));
1066       return -1;
1067     }
1068
1069   cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1070   
1071   if(!cl)
1072     {
1073       syslog(LOG_WARNING, _("Received UDP packets on port %hd from unknown source %x:%hd"), myself->port, ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1074       return 0;
1075     }
1076
1077   if(debug_lvl >= DEBUG_TRAFFIC)
1078     {
1079       syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1080              cl->name, cl->hostname);
1081     }
1082
1083 cp
1084   return xrecv(cl, &pkt);
1085 }
1086
1087 /*
1088   terminate a connection and notify the other
1089   end before closing the sockets
1090 */
1091 void terminate_connection(connection_t *cl)
1092 {
1093   connection_t *p;
1094   subnet_t *subnet;
1095   avl_node_t *node, *next;
1096 cp
1097   if(cl->status.remove)
1098     return;
1099
1100   if(debug_lvl >= DEBUG_CONNECTIONS)
1101     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1102            cl->name, cl->hostname);
1103  
1104   cl->status.remove = 1;
1105   
1106   if(cl->socket)
1107     close(cl->socket);
1108   if(cl->status.meta)
1109     close(cl->meta_socket);
1110
1111   if(cl->status.meta)
1112     {
1113     
1114       /* Find all connections that were lost because they were behind cl
1115          (the connection that was dropped). */
1116
1117         for(node = connection_tree->head; node; node = node->next)
1118           {
1119             p = (connection_t *)node->data;
1120             if(p->nexthop == cl && p != cl)
1121               terminate_connection(p);
1122           }
1123
1124       /* Inform others of termination if it was still active */
1125
1126       if(cl->status.active)
1127         for(node = connection_tree->head; node; node = node->next)
1128           {
1129             p = (connection_t *)node->data;
1130             if(p->status.meta && p->status.active && p != cl)
1131               send_del_host(p, cl);     /* Sounds like recursion, but p does not have a meta connection :) */
1132           }
1133     }
1134
1135   /* Remove the associated subnets */
1136
1137   for(node = cl->subnet_tree->head; node; node = next)
1138     {
1139       next = node->next;
1140       subnet = (subnet_t *)node->data;
1141       subnet_del(subnet);
1142     }
1143
1144   /* Check if this was our outgoing connection */
1145     
1146   if(cl->status.outgoing)
1147     {
1148       cl->status.outgoing = 0;
1149       signal(SIGALRM, sigalrm_handler);
1150       seconds_till_retry = 5;
1151       alarm(seconds_till_retry);
1152       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1153     }
1154
1155   /* Inactivate */
1156
1157   cl->status.active = 0;
1158 cp
1159 }
1160
1161 /*
1162   Check if the other end is active.
1163   If we have sent packets, but didn't receive any,
1164   then possibly the other end is dead. We send a
1165   PING request over the meta connection. If the other
1166   end does not reply in time, we consider them dead
1167   and close the connection.
1168 */
1169 void check_dead_connections(void)
1170 {
1171   time_t now;
1172   avl_node_t *node;
1173   connection_t *cl;
1174 cp
1175   now = time(NULL);
1176
1177   for(node = connection_tree->head; node; node = node->next)
1178     {
1179       cl = (connection_t *)node->data;
1180       if(cl->status.active && cl->status.meta)
1181         {
1182           if(cl->last_ping_time + timeout < now)
1183             {
1184               if(cl->status.pinged)
1185                 {
1186                   if(debug_lvl >= DEBUG_PROTOCOL)
1187                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1188                            cl->name, cl->hostname);
1189                   cl->status.timeout = 1;
1190                   terminate_connection(cl);
1191                 }
1192               else
1193                 {
1194                   send_ping(cl);
1195                 }
1196             }
1197         }
1198     }
1199 cp
1200 }
1201
1202 /*
1203   accept a new tcp connect and create a
1204   new connection
1205 */
1206 int handle_new_meta_connection()
1207 {
1208   connection_t *ncn;
1209   struct sockaddr client;
1210   int nfd, len = sizeof(client);
1211 cp
1212   if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1213     {
1214       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1215       return -1;
1216     }
1217
1218   if(!(ncn = create_new_connection(nfd)))
1219     {
1220       shutdown(nfd, 2);
1221       close(nfd);
1222       syslog(LOG_NOTICE, _("Closed attempted connection"));
1223       return 0;
1224     }
1225
1226   connection_add(ncn);
1227   
1228   send_id(ncn);
1229 cp
1230   return 0;
1231 }
1232
1233 /*
1234   check all connections to see if anything
1235   happened on their sockets
1236 */
1237 void check_network_activity(fd_set *f)
1238 {
1239   connection_t *p;
1240   avl_node_t *node;
1241 cp
1242   if(FD_ISSET(myself->socket, f))
1243     handle_incoming_vpn_data();
1244
1245   for(node = connection_tree->head; node; node = node->next)
1246     {
1247       p = (connection_t *)node->data;
1248
1249       if(p->status.remove)
1250         return;
1251
1252       if(p->status.meta)
1253         if(FD_ISSET(p->meta_socket, f))
1254           if(receive_meta(p) < 0)
1255             {
1256               terminate_connection(p);
1257               return;
1258             } 
1259     }
1260     
1261   if(FD_ISSET(myself->meta_socket, f))
1262     handle_new_meta_connection();
1263 cp
1264 }
1265
1266 /*
1267   read, encrypt and send data that is
1268   available through the ethertap device
1269 */
1270 void handle_tap_input(void)
1271 {
1272   vpn_packet_t vp;
1273   int lenin;
1274 cp  
1275   if(taptype == TAP_TYPE_TUNTAP)
1276     {
1277       if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1278         {
1279           syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1280           return;
1281         }
1282       vp.len = lenin;
1283     }
1284   else                  /* ethertap */
1285     {
1286       if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1287         {
1288           syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1289           return;
1290         }
1291       vp.len = lenin - 2;
1292     }
1293
1294   total_tap_in += lenin;
1295
1296   if(lenin < 32)
1297     {
1298       if(debug_lvl >= DEBUG_TRAFFIC)
1299         syslog(LOG_WARNING, _("Received short packet from tap device"));
1300       return;
1301     }
1302
1303   if(debug_lvl >= DEBUG_TRAFFIC)
1304     {
1305       syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1306     }
1307
1308   send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1309 cp
1310 }
1311
1312 /*
1313   this is where it all happens...
1314 */
1315 void main_loop(void)
1316 {
1317   fd_set fset;
1318   struct timeval tv;
1319   int r;
1320   time_t last_ping_check;
1321   int t;
1322 cp
1323   last_ping_check = time(NULL);
1324
1325   for(;;)
1326     {
1327       tv.tv_sec = timeout;
1328       tv.tv_usec = 0;
1329
1330       prune_connection_tree();
1331       build_fdset(&fset);
1332
1333       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1334         {
1335           if(errno != EINTR) /* because of alarm */
1336             {
1337               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1338               return;
1339             }
1340         }
1341
1342       if(sighup)
1343         {
1344           syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1345           sighup = 0;
1346           close_network_connections();
1347           clear_config(&config);
1348
1349           if(read_server_config())
1350             {
1351               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1352               exit(0);
1353             }
1354
1355           sleep(5);
1356           
1357           if(setup_network_connections())
1358             return;
1359             
1360           continue;
1361         }
1362
1363       t = time(NULL);
1364
1365       /* Let's check if everybody is still alive */
1366
1367       if(last_ping_check + timeout < t)
1368         {
1369           check_dead_connections();
1370           last_ping_check = time(NULL);
1371
1372           /* Should we regenerate our key? */
1373
1374           if(keyexpires < t)
1375             {
1376               if(debug_lvl >= DEBUG_STATUS)
1377                 syslog(LOG_INFO, _("Regenerating symmetric key"));
1378                 
1379               RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1380               send_key_changed(myself, NULL);
1381               keyexpires = time(NULL) + keylifetime;
1382             }
1383         }
1384
1385       if(r > 0)
1386         {
1387           check_network_activity(&fset);
1388
1389           /* local tap data */
1390           if(FD_ISSET(tap_fd, &fset))
1391             handle_tap_input();
1392         }
1393     }
1394 cp
1395 }