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