Conversion to struct addrinfo is almost complete for this file.
[tinc] / src / net.c
index fe9eed7..c7b612c 100644 (file)
--- a/src/net.c
+++ b/src/net.c
@@ -17,7 +17,7 @@
     along with this program; if not, write to the Free Software
     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
-    $Id: net.c,v 1.35.4.138 2001/10/27 13:13:35 guus Exp $
+    $Id: net.c,v 1.35.4.151 2001/11/16 22:41:38 zarq Exp $
 */
 
 #include "config.h"
@@ -33,6 +33,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <signal.h>
 #include <sys/signal.h>
 #include <sys/time.h>
 #include <sys/types.h>
@@ -62,7 +63,6 @@
 #include "connection.h"
 #include "meta.h"
 #include "net.h"
-#include "netutl.h"
 #include "process.h"
 #include "protocol.h"
 #include "subnet.h"
@@ -81,8 +81,40 @@ int udp_socket = -1;
 int keylifetime = 0;
 int keyexpires = 0;
 
+int do_prune = 0;
+
 /* VPN packet I/O */
 
+char *hostlookup(struct sockaddr *addr, int numericonly)
+{
+  char *hostname;
+  int flags = 0;
+  int r;
+
+cp
+  if(numericonly
+     || (get_config_bool(lookup_config(config_tree, "ResolveDNS"), &r)
+        || !r ))
+      flags |= NI_NUMERICHOST;
+
+  hostname = xmalloc(NI_MAXHOST);
+
+  if((r = getnameinfo(addr, sizeof(*addr), hostname, NI_MAXHOST, NULL, 0, flags)) != 0)
+    {
+      free(hostname);
+      if(flags & NI_NUMERICHOST)
+       {
+         syslog(LOG_ERR, _("Address conversion failed: %s"),
+                gai_strerror(r));
+         return NULL;
+       }
+      else
+       return hostlookup(addr, 1);
+    }
+cp
+  return hostname;
+}
+
 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
 {
   vpn_packet_t outpkt;
@@ -127,8 +159,6 @@ void send_udppacket(node_t *n, vpn_packet_t *inpkt)
   vpn_packet_t outpkt;
   int outlen, outpad;
   EVP_CIPHER_CTX ctx;
-  struct sockaddr_in to;
-  socklen_t tolen = sizeof(to);
   vpn_packet_t *copy;
 cp
   if(!n->status.validkey)
@@ -158,12 +188,8 @@ cp
   EVP_EncryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len + sizeof(inpkt->salt));
   EVP_EncryptFinal(&ctx, outpkt.salt + outlen, &outpad);
   outlen += outpad;
-
-  to.sin_family = AF_INET;
-  to.sin_addr.s_addr = htonl(n->address);
-  to.sin_port = htons(n->port);
-
-  if((sendto(udp_socket, (char *) outpkt.salt, outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
+  
+  if((sendto(udp_socket, (char *) outpkt.salt, outlen, 0, n->address->ai_addr, n->address->ai_addrlen)) < 0)
     {
       syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
              n->name, n->hostname);
@@ -192,32 +218,17 @@ cp
       return;
     }
 
-  if(!n->status.active)
-    {
-      if(debug_lvl >= DEBUG_TRAFFIC)
-       syslog(LOG_INFO, _("%s (%s) is not active, dropping packet"),
-              n->name, n->hostname);
-
-      return;
-    }
-/* FIXME
-  if(n->via == myself)
-    via = n->nexthop;
-  else
-    via = n->via;
-
-  if(via != n && debug_lvl >= DEBUG_TRAFFIC)
+  if(n->via != n && debug_lvl >= DEBUG_TRAFFIC)
     syslog(LOG_ERR, _("Sending packet to %s via %s (%s)"),
-           n->name, via->name, via->hostname);
+           n->name, n->via->name, n->via->hostname);
 
-  if((myself->options | via->options) & OPTION_TCPONLY)
+  if((myself->options | n->via->options) & OPTION_TCPONLY)
     {
-      if(send_tcppacket(via->connection, packet))
-        terminate_connection(via->connection, 1);
+      if(send_tcppacket(n->via->connection, packet))
+        terminate_connection(n->via->connection, 1);
     }
   else
-    send_udppacket(via, packet);
-*/
+    send_udppacket(n->via, packet);
 }
 
 /* Broadcast a packet to all active direct connections */
@@ -258,116 +269,191 @@ cp
 
 /* Setup sockets */
 
-int setup_listen_socket(int port)
+int setup_listen_socket(node_t *n)
 {
   int nfd, flags;
-  struct sockaddr_in a;
   int option;
-  char *interface;
   char *address;
-  ip_mask_t *ipmask;
+  int r;
+  struct addrinfo hints, *ai, *aitop;
+  int ipv6preferred;
+#ifdef HAVE_LINUX
+  char *interface;
+#endif
+
 cp
-  if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
+
+  if(!get_config_string(lookup_config(config_tree, "BindToAddress"), &address))
     {
-      syslog(LOG_ERR, _("Creating metasocket failed: %m"));
-      return -1;
+      address = NULL;
     }
 
-  flags = fcntl(nfd, F_GETFL);
-  if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
+  hints.ai_socktype = SOCK_STREAM;
+  hints.ai_protocol = IPPROTO_TCP;
+  hints.ai_family = AF_INET;
+  if(get_config_bool(lookup_config(config_tree, "IPv6Preferred"), &ipv6preferred))
     {
-      close(nfd);
-      syslog(LOG_ERR, _("System call `%s' failed: %m"),
-            "fcntl");
+      if(ipv6preferred)
+       hints.ai_family = PF_UNSPEC;
+    }
+  if((r = getaddrinfo(address, n->port, &hints, &aitop)) != 0)
+    {
+      syslog(LOG_ERR, _("Looking up `%s' failed: %s\n"),
+            address, gai_strerror(r));
       return -1;
     }
 
-  /* Optimize TCP settings */
-
-  option = 1;
-  setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
-  setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
+  /* Try to create a listening socket for all alternatives we got from
+     getaddrinfo. */
+  for(ai = aitop; ai != NULL; ai = ai->ai_next)
+    {
+      if((nfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0)
+       {
+         syslog(LOG_ERR, _("Creating metasocket failed: %m"));
+         continue;
+       }
+      
+      flags = fcntl(nfd, F_GETFL);
+      if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
+       {
+         close(nfd);
+         syslog(LOG_ERR, _("System call `%s' failed: %m"),
+                "fcntl");
+         continue;
+       }
+      
+      /* Optimize TCP settings */
+      
+      option = 1;
+      setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
+      setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
 #ifdef HAVE_LINUX
-  setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
-
-  option = IPTOS_LOWDELAY;
-  setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
-
-  if(get_config_string(lookup_config(config_tree, "BindToInterface"), &interface))
-    if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)))
-      {
-        close(nfd);
-        syslog(LOG_ERR, _("Can't bind to interface %s: %m"), interface);
-        return -1;
-      }
+      setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
+      
+      option = IPTOS_LOWDELAY;
+      setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
+      
+      if(get_config_string(lookup_config(config_tree, "BindToInterface"), &interface))
+       if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)))
+         {
+           close(nfd);
+           syslog(LOG_ERR, _("Can't bind to interface %s: %m"), interface);
+           continue;
+         }
 #endif
 
-  memset(&a, 0, sizeof(a));
-  a.sin_family = AF_INET;
-  a.sin_addr.s_addr = htonl(INADDR_ANY);
-  a.sin_port = htons(port);
-
-  if(get_config_string(lookup_config(config_tree, "BindToAddress"), &address))
-    {
-      ipmask = strtoip(address);
-      if(ipmask)
-      {
-        a.sin_addr.s_addr = htonl(ipmask->address);
-        free(ipmask);
-      }
-    }
+      if(bind(nfd, ai->ai_addr, ai->ai_addrlen))
+       {
+         close(nfd);
+         syslog(LOG_ERR, _("Can't bind to %s port %s/tcp: %m"),
+                ai->ai_canonname, n->port);
+         continue;
+       }
+      
+      if(listen(nfd, 3))
+       {
+         close(nfd);
+         syslog(LOG_ERR, _("System call `%s' failed: %m"),
+                "listen");
+         continue;
+       }
 
-  if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
-    {
-      close(nfd);
-      syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
-      return -1;
+      break; /* We have successfully bound to a socket */
     }
 
-  if(listen(nfd, 3))
+  if(ai == NULL) /* None of the alternatives succeeded */
     {
-      close(nfd);
-      syslog(LOG_ERR, _("System call `%s' failed: %m"),
-            "listen");
+      syslog(LOG_ERR, _("Failed to open a listening socket."));
       return -1;
     }
 cp
   return nfd;
 }
 
-int setup_vpn_in_socket(int port)
+int setup_vpn_in_socket(node_t *n)
 {
-  int nfd, flags;
-  struct sockaddr_in a;
   const int one = 1;
+  int nfd, flags;
+  int option;
+  char *address;
+  int r;
+  struct addrinfo hints, *ai, *aitop;
+  int ipv6preferred;
+#ifdef HAVE_LINUX
+  char *interface;
+#endif
+
 cp
-  if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
+
+  if(!get_config_string(lookup_config(config_tree, "BindToAddress"), &address))
+    {
+      address = NULL;
+    }
+
+  hints.ai_socktype = SOCK_DGRAM;
+  hints.ai_protocol = IPPROTO_UDP;
+  hints.ai_family = AF_INET;
+  if(get_config_bool(lookup_config(config_tree, "IPv6Preferred"), &ipv6preferred))
     {
-      close(nfd);
-      syslog(LOG_ERR, _("Creating socket failed: %m"));
+      if(ipv6preferred)
+       hints.ai_family = PF_UNSPEC;
+    }
+  if((r = getaddrinfo(address, n->port, &hints, &aitop)) != 0)
+    {
+      syslog(LOG_ERR, _("Looking up `%s' failed: %s\n"),
+            address, gai_strerror(r));
       return -1;
     }
 
   setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
 
-  flags = fcntl(nfd, F_GETFL);
-  if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
+  /* Try to create a listening socket for all alternatives we got from
+     getaddrinfo. */
+  for(ai = aitop; ai != NULL; ai = ai->ai_next)
     {
-      close(nfd);
-      syslog(LOG_ERR, _("System call `%s' failed: %m"),
-            "fcntl");
-      return -1;
-    }
+      if((nfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0)
+       {
+         syslog(LOG_ERR, _("Creating metasocket failed: %m"));
+         continue;
+       }
+      
+      flags = fcntl(nfd, F_GETFL);
+      if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
+       {
+         close(nfd);
+         syslog(LOG_ERR, _("System call `%s' failed: %m"),
+                "fcntl");
+         continue;
+       }
+      
+      /* Optimize UDP settings */
+      
+      option = 1;
+      setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
+#ifdef HAVE_LINUX
+      if(get_config_string(lookup_config(config_tree, "BindToInterface"), &interface))
+       if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)))
+         {
+           close(nfd);
+           syslog(LOG_ERR, _("Can't bind to interface %s: %m"), interface);
+           continue;
+         }
+#endif
 
-  memset(&a, 0, sizeof(a));
-  a.sin_family = AF_INET;
-  a.sin_port = htons(port);
-  a.sin_addr.s_addr = htonl(INADDR_ANY);
+      if(bind(nfd, ai->ai_addr, ai->ai_addrlen))
+       {
+         close(nfd);
+         syslog(LOG_ERR, _("Can't bind to %s port %s/tcp: %m"),
+                ai->ai_canonname, n->port);
+         continue;
+       }
+      
+      break; /* We have successfully bound to a socket */
+    }
 
-  if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
+  if(ai == NULL) /* None of the alternatives succeeded */
     {
-      close(nfd);
-      syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
+      syslog(LOG_ERR, _("Failed to open a listening socket."));
       return -1;
     }
 cp
@@ -377,8 +463,6 @@ cp
 int setup_outgoing_socket(connection_t *c)
 {
   int flags;
-  struct sockaddr_in a;
-  int option;
 cp
   if(debug_lvl >= DEBUG_CONNECTIONS)
     syslog(LOG_INFO, _("Trying to connect to %s (%s)"), c->name, c->hostname);
@@ -387,7 +471,7 @@ cp
 
   if(c->socket == -1)
     {
-      syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
+      syslog(LOG_ERR, _("Creating socket for %s port %s failed: %m"),
              c->hostname, c->port);
       return -1;
     }
@@ -422,14 +506,10 @@ cp
 
   /* Connect */
 
-  a.sin_family = AF_INET;
-  a.sin_port = htons(c->port);
-  a.sin_addr.s_addr = htonl(c->address);
-
-  if(connect(c->socket, (struct sockaddr *)&a, sizeof(a)) == -1)
+  if(connect(c->socket, c->address->ai_addr, c->address->ai_addrlen) == -1)
     {
       close(c->socket);
-      syslog(LOG_ERR, _("%s port %hd: %m"), c->hostname, c->port);
+      syslog(LOG_ERR, _("%s port %s: %m"), c->hostname, c->port);
       return -1;
     }
 
@@ -438,13 +518,13 @@ cp
   if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0)
     {
       close(c->socket);
-      syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
+      syslog(LOG_ERR, _("fcntl for %s port %s: %m"),
              c->hostname, c->port);
       return -1;
     }
 
   if(debug_lvl >= DEBUG_CONNECTIONS)
-    syslog(LOG_INFO, _("Connected to %s port %hd"),
+    syslog(LOG_INFO, _("Connected to %s port %s"),
          c->hostname, c->port);
 cp
   return 0;
@@ -453,11 +533,25 @@ cp
 int setup_outgoing_connection(char *name)
 {
   connection_t *c;
-  struct hostent *h;
+  node_t *n;
+  struct addrinfo *ai, *aitop, hints;
+  int r, ipv6preferred;
+
 cp
+  n = lookup_node(name);
+  
+  if(n)
+    if(n->connection)
+      {
+        if(debug_lvl >= DEBUG_CONNECTIONS)       
+          syslog(LOG_INFO, _("Already connected to %s"), name);
+        return 0;
+      }
+
   c = new_connection();
   c->name = xstrdup(name);
 
+  init_configuration(&c->config_tree);
   read_connection_config(c);
   
   if(!get_config_string(lookup_config(c->config_tree, "Address"), &c->hostname))
@@ -467,27 +561,37 @@ cp
       return -1;
     }
 
-  if(!get_config_port(lookup_config(c->config_tree, "Port"), &c->port))
+  if(!get_config_string(lookup_config(c->config_tree, "Port"), &c->port))
     {
       syslog(LOG_ERR, _("No port specified for %s"), c->name);
       free_connection(c);
       return -1;
     }
 
-  if(!(h = gethostbyname(c->hostname)))
+  hints.ai_socktype = SOCK_STREAM;
+  hints.ai_family = AF_INET;
+  if(get_config_bool(lookup_config(c->config_tree, "IPv6Preferred"), &ipv6preferred))
     {
-      syslog(LOG_ERR, _("Error looking up `%s': %m"), c->hostname);
-      free_connection(c);
+      if(ipv6preferred)
+       hints.ai_family = PF_UNSPEC;
+    }
+
+  if((r = getaddrinfo(c->hostname, c->port, &hints, &aitop)) != 0)
+    {
+      syslog(LOG_ERR, _("Looking up %s failed: %s\n"),
+            c->hostname, gai_strerror(r));
       return -1;
     }
 
-  c->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
-  c->hostname = hostlookup(htonl(c->address));
+  for(ai = aitop; ai != NULL; ai = ai->ai_next)
+    {
+      if(setup_outgoing_socket(c) < 0)
+       continue;
+    }
 
-  if(setup_outgoing_socket(c) < 0)
+  if(ai == NULL)
     {
-      syslog(LOG_ERR, _("Could not set up a meta connection to %s (%s)"),
-             c->name, c->hostname);
+      /* No connection alternative succeeded */
       free_connection(c);
       return -1;
     }
@@ -507,7 +611,6 @@ int read_rsa_public_key(connection_t *c)
   FILE *fp;
   char *fname;
   char *key;
-  void *result;
 cp
   if(!c->rsa_key)
     c->rsa_key = RSA_new();
@@ -533,9 +636,9 @@ cp
                     fname);
               return -1;
             }
-          result = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
+          c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
           fclose(fp);
-          if(!result)
+          if(!c->rsa_key)
             {
               syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
                     fname);
@@ -549,19 +652,16 @@ cp
 
   /* Else, check if a harnessed public key is in the config file */
 
-  result = NULL;
-
   asprintf(&fname, "%s/hosts/%s", confbase, c->name);
   if((fp = fopen(fname, "r")))
     {
-      result = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
+      c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
       fclose(fp);
-      free(fname);
     }
 
   free(fname);
 
-  if(result)
+  if(c->rsa_key)
     return 0;
   else
     {
@@ -573,14 +673,11 @@ cp
 int read_rsa_private_key(void)
 {
   FILE *fp;
-  void *result;
   char *fname, *key;
 cp
-  if(!myself->connection->rsa_key)
-    myself->connection->rsa_key = RSA_new();
-
   if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key))
     {
+      myself->connection->rsa_key = RSA_new();
       BN_hex2bn(&myself->connection->rsa_key->d, key);
       BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
     }
@@ -592,9 +689,9 @@ cp
                 fname);
           return -1;
         }
-      result = PEM_read_RSAPrivateKey(fp, &myself->connection->rsa_key, NULL, NULL);
+      myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
       fclose(fp);
-      if(!result)
+      if(!myself->connection->rsa_key)
         {
           syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
                 fname);
@@ -622,6 +719,7 @@ int setup_myself(void)
 cp
   myself = new_node();
   myself->connection = new_connection();
+  init_configuration(&myself->connection->config_tree);
 
   asprintf(&myself->hostname, _("MYSELF"));
   asprintf(&myself->connection->hostname, _("MYSELF"));
@@ -666,8 +764,10 @@ cp
       return -1;
     }
 */
-  if(!get_config_port(lookup_config(myself->connection->config_tree, "Port"), &myself->connection->port))
-    myself->port = 655;
+  if(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myself->port))
+    myself->port = "655";
+
+  myself->connection->port = myself->port;
 
 /* Read in all the subnets specified in the host configuration file */
 
@@ -705,7 +805,7 @@ cp
   if(myself->options & OPTION_TCPONLY)
     myself->options |= OPTION_INDIRECT;
 
-  if(get_config_string(lookup_config(myself->connection->config_tree, "Mode"), &mode))
+  if(get_config_string(lookup_config(config_tree, "Mode"), &mode))
     {
       if(!strcasecmp(mode, "router"))
         routing_mode = RMODE_ROUTER;
@@ -725,13 +825,13 @@ cp
 cp
   /* Open sockets */
   
-  if((tcp_socket = setup_listen_socket(myself->port)) < 0)
+  if((tcp_socket = setup_listen_socket(myself)) < 0)
     {
       syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
       return -1;
     }
 
-  if((udp_socket = setup_vpn_in_socket(myself->port)) < 0)
+  if((udp_socket = setup_vpn_in_socket(myself)) < 0)
     {
       syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
       return -1;
@@ -746,7 +846,7 @@ cp
   myself->key = (char *)xmalloc(myself->keylength);
   RAND_pseudo_bytes(myself->key, myself->keylength);
 
-  if(!get_config_int(lookup_config(myself->connection->config_tree, "KeyExpire"), &keylifetime))
+  if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
     keylifetime = 3600;
 
   keyexpires = time(NULL) + keylifetime;
@@ -758,7 +858,7 @@ cp
   myself->status.active = 1;
   node_add(myself);
 
-  syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
+  syslog(LOG_NOTICE, _("Ready: listening on port %s"), myself->port);
 cp
   return 0;
 }
@@ -771,8 +871,10 @@ int setup_network_connections(void)
 cp
   init_connections();
   init_subnets();
+  init_nodes();
+  init_edges();
 
-  if(get_config_int(lookup_config(myself->connection->config_tree, "PingTimeout"), &timeout))
+  if(get_config_int(lookup_config(config_tree, "PingTimeout"), &timeout))
     {
       if(timeout < 1)
         {
@@ -813,9 +915,15 @@ cp
       terminate_connection(c, 0);
     }
 
-//  terminate_connection(myself, 0);
+  terminate_connection(myself->connection, 0);
 
-//  destroy_trees();
+  close(udp_socket);
+  close(tcp_socket);
+
+  exit_edges();
+  exit_subnets();
+  exit_nodes();
+  exit_connections();
 
   execute_script("tinc-down");
 
@@ -844,15 +952,22 @@ cp
       return NULL;
     }
 
-  c->address = ntohl(ci.sin_addr.s_addr);
-  c->hostname = hostlookup(ci.sin_addr.s_addr);
-  c->port = htons(ci.sin_port);                                /* This one will be overwritten later */
+  c->address = sockaddr_to_addrinfo(ci);
+
+  c->hostname = xmalloc(INET6_ADDRSTRLEN);
+  if((inet_ntop(ci.sin_family, &(ci.sin_addr), c->hostname, INET6_ADDRSTRLEN)) == NULL)
+    {
+      syslog(LOG_ERR, _("Couldn't convert address to string: %m"));
+      free(c->hostname);
+      return NULL;
+    }
+  asprintf(&(c->port), "%d", htons(ci.sin_port));
   c->socket = sfd;
   c->last_ping_time = time(NULL);
 
   if(debug_lvl >= DEBUG_CONNECTIONS)
-    syslog(LOG_NOTICE, _("Connection from %s port %d"),
-         c->hostname, htons(ci.sin_port));
+    syslog(LOG_NOTICE, _("Connection from %s port %s"),
+         c->hostname, c->port);
 
   c->allow_request = ID;
 cp
@@ -912,11 +1027,11 @@ cp
       return;
     }
 
-  n = lookup_node_udp(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
+  n = lookup_node_udp(sockaddr_to_addrinfo(&from));
 
   if(!n)
     {
-      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));
+      syslog(LOG_WARNING, _("Received UDP packet on port %s from unknown source %x:%hd"), myself->port, ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
       return;
     }
 /*
@@ -929,15 +1044,60 @@ cp
 
 /*
   Terminate a connection:
-  - Close the sockets
-  - Remove associated hosts and subnets
+  - Close the socket
+  - Remove associated edge and tell other connections about it if report = 1
+  - Check if we need to retry making an outgoing connection
   - Deactivate the host
-  - Since it might still be referenced, put it on the prune list.
-  - If report == 1, then send DEL_HOST messages to the other tinc daemons.
 */
 void terminate_connection(connection_t *c, int report)
 {
-  /* Needs a serious rewrite. */
+  avl_node_t *node;
+  connection_t *other;
+cp
+  if(c->status.remove)
+    return;
+  
+  if(debug_lvl >= DEBUG_CONNECTIONS)
+    syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
+           c->name, c->hostname);
+
+  c->status.remove = 1;
+  
+  if(c->socket)
+    close(c->socket);
+
+  if(c->edge)
+    {
+      if(report)
+        {
+          for(node = connection_tree->head; node; node = node->next)
+            {
+              other = (connection_t *)node->data;
+              if(other->status.active && other != c)
+                send_del_edge(other, c->edge);
+            }
+        }
+
+      edge_del(c->edge);
+    }
+
+  /* Check if this was our outgoing connection */
+
+  if(c->status.outgoing)
+    {
+      c->status.outgoing = 0;
+      signal(SIGALRM, try_outgoing_connections);
+      alarm(seconds_till_retry);
+      syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
+    }
+
+  /* Deactivate */
+
+  c->status.active = 0;
+  if(c->node)
+    c->node->connection = NULL;
+  do_prune = 1;
+cp
 }
 
 /*
@@ -1053,11 +1213,17 @@ cp
   while(cfg)
     {
       get_config_string(cfg, &name);
-      cfg = lookup_config_next(config_tree, cfg);  /* Next time skip to next ConnectTo line */
 
-      if(!setup_outgoing_connection(name))   /* function returns 0 when there are no problems */
+      if(check_id(name))
+        {
+          syslog(LOG_ERR, _("Invalid name for outgoing connection in %s line %d"), cfg->file, cfg->line);
+          continue;
+        }
+
+      if(setup_outgoing_connection(name))   /* function returns 0 when there are no problems */
         retry = 1;
 
+      cfg = lookup_config_next(config_tree, cfg); /* Next time skip to next ConnectTo line */
     }
 
   get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout);
@@ -1068,7 +1234,7 @@ cp
       if(seconds_till_retry > maxtimeout)    /* Don't wait more than MAXTIMEOUT seconds. */
         seconds_till_retry = maxtimeout;
 
-      syslog(LOG_ERR, _("Failed to setup all outgoing connections, will retry in %d seconds"),
+      syslog(LOG_ERR, _("Failed to setup any outgoing connection, will retry in %d seconds"),
         seconds_till_retry);
   
       /* Randomize timeout to avoid global synchronisation effects */
@@ -1113,6 +1279,22 @@ cp
 cp
 }
 
+void prune_connections(void)
+{
+  connection_t *c;
+  avl_node_t *node, *next;
+cp
+  for(node = connection_tree->head; node; node = next)
+    {
+      next = node->next;
+      c = (connection_t *)node->data;
+
+      if(c->status.remove)
+       connection_del(c);
+    }
+cp
+}
+
 /*
   this is where it all happens...
 */
@@ -1132,6 +1314,12 @@ cp
       tv.tv_sec = timeout;
       tv.tv_usec = 0;
 
+      if(do_prune)
+        {
+          prune_connections();
+          do_prune = 0;
+        }
+
       build_fdset(&fset);
 
       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
@@ -1194,9 +1382,9 @@ cp
           if(FD_ISSET(device_fd, &fset))
             {
               if(read_packet(&packet))
-                route_outgoing(&packet);
-              else
                 return;
+              else
+                route_outgoing(&packet);
             }
         }
     }