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