]> git.meshlink.io Git - meshlink/commitdiff
Merge branch 'master' into 1.1
authorGuus Sliepen <guus@sliepen.eu.org>
Wed, 16 Sep 2009 17:55:47 +0000 (19:55 +0200)
committerGuus Sliepen <guus@sliepen.eu.org>
Wed, 16 Sep 2009 17:55:47 +0000 (19:55 +0200)
Conflicts:
have.h
lib/dropin.c
lib/fake-getaddrinfo.c
lib/pidfile.c
src/Makefile.am
src/bsd/device.c
src/conf.c
src/connection.c
src/connection.h
src/graph.c
src/mingw/device.c
src/net.c
src/net_setup.c
src/node.c
src/protocol_key.c
src/protocol_misc.c
src/tincd.c

33 files changed:
1  2 
configure.in
have.h
lib/dropin.c
lib/fake-getaddrinfo.c
lib/fake-getnameinfo.c
lib/utils.c
src/Makefile.am
src/bsd/device.c
src/conf.c
src/connection.c
src/connection.h
src/graph.c
src/meta.c
src/mingw/device.c
src/net.h
src/net_packet.c
src/net_setup.c
src/net_socket.c
src/netutl.c
src/node.c
src/node.h
src/process.c
src/protocol.c
src/protocol_edge.c
src/protocol_key.c
src/protocol_misc.c
src/protocol_subnet.c
src/route.c
src/solaris/device.c
src/subnet.c
src/tincctl.c
src/tincd.c
src/uml_socket/device.c

diff --cc configure.in
Simple merge
diff --cc have.h
Simple merge
diff --cc lib/dropin.c
Simple merge
index 0c27025bd19fdce5e92e83a35189dd73d252664e,10672b7e6f07eee8749a120c66eeff1a2703cbf8..df3d34764dc9680dd1d625cd10ed94e2bdfb19d0
@@@ -16,8 -16,9 +16,9 @@@
  #include "fake-getaddrinfo.h"
  #include "xalloc.h"
  
- #ifndef HAVE_GAI_STRERROR
++
+ #if !HAVE_DECL_GAI_STRERROR
 -char *gai_strerror(int ecode)
 -{
 +char *gai_strerror(int ecode) {
        switch (ecode) {
                case EAI_NODATA:
                        return "No address associated with hostname";
@@@ -31,8 -32,9 +32,8 @@@
  }    
  #endif /* !HAVE_GAI_STRERROR */
  
- #ifndef HAVE_FREEADDRINFO
+ #if !HAVE_DECL_FREEADDRINFO
 -void freeaddrinfo(struct addrinfo *ai)
 -{
 +void freeaddrinfo(struct addrinfo *ai) {
        struct addrinfo *next;
  
        while(ai) {
@@@ -43,8 -45,9 +44,8 @@@
  }
  #endif /* !HAVE_FREEADDRINFO */
  
- #ifndef HAVE_GETADDRINFO
+ #if !HAVE_DECL_GETADDRINFO
 -static struct addrinfo *malloc_ai(uint16_t port, uint32_t addr)
 -{
 +static struct addrinfo *malloc_ai(uint16_t port, uint32_t addr) {
        struct addrinfo *ai;
  
        ai = xmalloc_and_zero(sizeof(struct addrinfo) + sizeof(struct sockaddr_in));
index 05f0875aec49e92ccc277f997ce13de2be1d27e9,804717309c809c05953a425f9c2e4ce5c9121e25..1eba49253ea387638844de3457e2efbdeb008e4e
  #include "fake-getnameinfo.h"
  #include "fake-getaddrinfo.h"
  
- #ifndef HAVE_GETNAMEINFO
+ #if !HAVE_DECL_GETNAMEINFO
  
 -int getnameinfo(const struct sockaddr *sa, size_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags)
 -{
 +int getnameinfo(const struct sockaddr *sa, size_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags) {
        struct sockaddr_in *sin = (struct sockaddr_in *)sa;
        struct hostent *hp;
        int len;
diff --cc lib/utils.c
Simple merge
diff --cc src/Makefile.am
index ed110e9f15c3359bc622186b577f632de0c13762,501fdf66953875873d88289e60dc36ea26308961..db90897ff60d1d01c71d20cf8f15d176880a1a20
@@@ -5,23 -5,29 +5,31 @@@ sbin_PROGRAMS = tincd tincct
  
  EXTRA_DIST = linux/device.c bsd/device.c solaris/device.c cygwin/device.c mingw/device.c mingw/common.h raw_socket/device.c uml_socket/device.c
  
 -tincd_SOURCES = conf.c connection.c edge.c event.c graph.c logger.c meta.c net.c net_packet.c net_setup.c     \
 +tincd_SOURCES = cipher.c conf.c connection.c control.c crypto.c digest.c edge.c graph.c logger.c meta.c net.c net_packet.c net_setup.c        \
        net_socket.c netutl.c node.c process.c protocol.c protocol_auth.c protocol_edge.c protocol_misc.c       \
 -      protocol_key.c protocol_subnet.c route.c subnet.c tincd.c
 +      protocol_key.c protocol_subnet.c route.c rsa.c subnet.c tincd.c
 +
 +tincctl_SOURCES = tincctl.c rsagen.c
  
+ if TUNEMU
+ tincd_SOURCES += bsd/tunemu.c
+ endif
  nodist_tincd_SOURCES = device.c
  
  DEFAULT_INCLUDES =
  
  INCLUDES = @INCLUDES@ -I$(top_builddir) -I$(top_srcdir)/lib
  
 -noinst_HEADERS = conf.h connection.h device.h edge.h event.h graph.h logger.h meta.h net.h netutl.h node.h process.h  \
 -      protocol.h route.h subnet.h bsd/tunemu.h
 +noinst_HEADERS = cipher.h conf.h connection.h control.h crypto.h device.h digest.h edge.h graph.h logger.h meta.h net.h netutl.h node.h process.h     \
-       protocol.h route.h rsa.h rsagen.h subnet.h
++      protocol.h route.h rsa.h rsagen.h subnet.h bsd/tunemu.h
  
 -LIBS = @LIBS@ @LIBINTL@
 +LIBS = @LIBS@ @LIBGCRYPT_LIBS@ @LIBINTL@
  
+ if TUNEMU
+ LIBS += -lpcap
+ endif
  tincd_LDADD = \
        $(top_builddir)/lib/libvpn.a
  
index 1066858bed2620d2ef979b6480fa69978a2b4814,fe85d10fc534a166244457dbd01e0512b81c8afb..872ad92f818a6e26f69a5672d7d715d92bc409d6
@@@ -152,7 -190,16 +190,16 @@@ bool read_packet(vpn_packet_t *packet) 
  
        switch(device_type) {
                case DEVICE_TYPE_TUN:
-                       if((inlen = read(device_fd, packet->data + 14, MTU - 14)) <= 0) {
+ #ifdef HAVE_TUNEMU
+               case DEVICE_TYPE_TUNEMU:
+                       if(device_type == DEVICE_TYPE_TUNEMU)
 -                              lenin = tunemu_read(device_fd, packet->data + 14, MTU - 14);
++                              inlen = tunemu_read(device_fd, packet->data + 14, MTU - 14);
+                       else
+ #else
 -                              lenin = read(device_fd, packet->data + 14, MTU - 14);
++                              inlen = read(device_fd, packet->data + 14, MTU - 14);
+ #endif
 -                      if(lenin <= 0) {
++                      if(inlen <= 0) {
                                logger(LOG_ERR, _("Error while reading from %s %s: %s"), device_info,
                                           device, strerror(errno));
                                return false;
diff --cc src/conf.c
Simple merge
index 230ec4ede6b48ca3ae3560ba3ae0844c5407f647,283ebd7127d2462a8cc3ff3b3ddedf3347f659b6..4a2ba4c09110394e8654f4ecc3728484878ddf3f
  #include "utils.h"
  #include "xalloc.h"
  
 -avl_tree_t *connection_tree;  /* Meta connections */
 +splay_tree_t *connection_tree;        /* Meta connections */
  connection_t *broadcast;
  
 -static int connection_compare(const connection_t *a, const connection_t *b)
 -{
 +static int connection_compare(const connection_t *a, const connection_t *b) {
-       return (void *)a - (void *)b;
+       return a < b ? -1 : a == b ? 0 : 1;
  }
  
 -void init_connections(void)
 -{
 +void init_connections(void) {
        cp();
  
 -      connection_tree = avl_alloc_tree((avl_compare_t) connection_compare, (avl_action_t) free_connection);
 +      connection_tree = splay_alloc_tree((splay_compare_t) connection_compare, (splay_action_t) free_connection);
        broadcast = new_connection();
        broadcast->name = xstrdup(_("everyone"));
        broadcast->hostname = xstrdup(_("BROADCAST"));
@@@ -110,19 -139,20 +110,19 @@@ int dump_connections(struct evbuffer *o
  
        cp();
  
 -      logger(LOG_DEBUG, _("Connections:"));
 -
        for(node = connection_tree->head; node; node = node->next) {
                c = node->data;
 -              logger(LOG_DEBUG, _(" %s at %s options %lx socket %d status %04x outbuf %d/%d/%d"),
 -                         c->name, c->hostname, c->options, c->socket, bitfield_to_int(&c->status, sizeof c->status),
 -                         c->outbufsize, c->outbufstart, c->outbuflen);
 +              if(evbuffer_add_printf(out,
 +                                 _(" %s at %s options %lx socket %d status %04x\n"),
 +                                 c->name, c->hostname, c->options, c->socket,
-                                  c->status.value) == -1)
++                                 bitfield_to_int(&c->status, sizeof c->status)) == -1)
 +                      return errno;
        }
  
 -      logger(LOG_DEBUG, _("End of connections."));
 +      return 0;
  }
  
 -bool read_connection_config(connection_t *c)
 -{
 +bool read_connection_config(connection_t *c) {
        char *fname;
        int x;
  
index 08778bf3fda5bdf8f9069ffa6521964e0e47afa3,8948d4fae885589205c74c7c2348a79f071a8f05..e44af0b06a2412c9c021114dac35985404b48c40
  #define OPTION_TCPONLY                0x0002
  #define OPTION_PMTU_DISCOVERY 0x0004
  
- typedef union connection_status_t {
-       struct {
+ typedef struct connection_status_t {
 -      int pinged:1;                           /* sent ping */
 -      int active:1;                           /* 1 if active.. */
 -      int connecting:1;                       /* 1 if we are waiting for a non-blocking connect() to finish */
 -      int termreq:1;                          /* the termination of this connection was requested */
 -      int remove:1;                           /* Set to 1 if you want this connection removed */
 -      int timeout:1;                          /* 1 if gotten timeout */
 -      int encryptout:1;                       /* 1 if we can encrypt outgoing traffic */
 -      int decryptin:1;                        /* 1 if we have to decrypt incoming traffic */
 -      int mst:1;                              /* 1 if this connection is part of a minimum spanning tree */
 -      int unused:23;
 +              int pinged:1;                           /* sent ping */
 +              int active:1;                           /* 1 if active.. */
 +              int connecting:1;                       /* 1 if we are waiting for a non-blocking connect() to finish */
 +              int termreq:1;                          /* the termination of this connection was requested */
 +              int remove_unused:1;                            /* Set to 1 if you want this connection removed */
 +              int timeout_unused:1;                           /* 1 if gotten timeout */
 +              int encryptout:1;                       /* 1 if we can encrypt outgoing traffic */
 +              int decryptin:1;                        /* 1 if we have to decrypt incoming traffic */
 +              int mst:1;                              /* 1 if this connection is part of a minimum spanning tree */
 +              int unused:23;
-       };
-       uint32_t value;
  } connection_status_t;
  
  #include "edge.h"
diff --cc src/graph.c
index 4e060b7ffa9c647cd4cc3103085e3e542ddf3ef7,a267f052a196df31c1d797ca1e5cf0dc965d11d9..f2e546ee9b4e1463f4490f713a3bb90d316dc06e
  #include "process.h"
  #include "subnet.h"
  #include "utils.h"
+ #include "xalloc.h"
  
 -static bool graph_changed = true;
 -
  /* Implementation of Kruskal's algorithm.
 -   Running time: O(EN)
 +   Running time: O(E)
     Please note that sorting on weight is already done by add_edge().
  */
  
@@@ -359,13 -265,18 +360,15 @@@ void check_reachability() 
                        n->minmtu = 0;
                        n->mtuprobes = 0;
  
-                       asprintf(&envp[0], "NETNAME=%s", netname ? : "");
-                       asprintf(&envp[1], "DEVICE=%s", device ? : "");
-                       asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
-                       asprintf(&envp[3], "NODE=%s", n->name);
 -                      if(n->mtuevent) {
 -                              event_del(n->mtuevent);
 -                              n->mtuevent = NULL;
 -                      }
++                      event_del(&n->mtuevent);
+                       xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
+                       xasprintf(&envp[1], "DEVICE=%s", device ? : "");
+                       xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
+                       xasprintf(&envp[3], "NODE=%s", n->name);
                        sockaddr2str(&n->address, &address, &port);
-                       asprintf(&envp[4], "REMOTEADDRESS=%s", address);
-                       asprintf(&envp[5], "REMOTEPORT=%s", port);
+                       xasprintf(&envp[4], "REMOTEADDRESS=%s", address);
+                       xasprintf(&envp[5], "REMOTEPORT=%s", port);
                        envp[6] = NULL;
  
                        execute_script(n->status.reachable ? "host-up" : "host-down", envp);
diff --cc src/meta.c
index 82dde3a54442ef73f933e1f607138fd52eab1966,b59f15b09443f47596d8e60454686e262c5298b7..6054427ce62b0d64b8a283f109afc7dfe7a3c3c7
  #include "utils.h"
  #include "xalloc.h"
  
 -bool send_meta(connection_t *c, const char *buffer, int length)
 -{
 -      int outlen;
 -      int result;
 -
 +bool send_meta(connection_t *c, const char *buffer, int length) {
        cp();
  
+       if(!c) {
+               logger(LOG_ERR, _("send_meta() called with NULL pointer!"));
+               abort();
+       }
        ifdebug(META) logger(LOG_DEBUG, _("Sending %d bytes of metadata to %s (%s)"), length,
                           c->name, c->hostname);
  
index 915256f502d4a18108cf199f87ca19011c11750f,fa13433230fb2e1c66e7ccd15829ede8c8e9be2f..2334af3913c49a5a71248a3045008c1bd7fb185b
@@@ -316,30 -232,14 +230,12 @@@ void close_device(void) 
        free(iface);
  }
  
 -bool read_packet(vpn_packet_t *packet)
 -{
 +bool read_packet(vpn_packet_t *packet) {
-       unsigned char bufno;
-       cp();
-       if((recv(device_fd, &bufno, 1, 0)) <= 0) {
-               logger(LOG_ERR, _("Error while reading from %s %s: %s"), device_info,
-                          device, strerror(errno));
-               return false;
-       }
-       
-       packet->len = bufs[bufno].len;
-       memcpy(packet->data, bufs[bufno].data, bufs[bufno].len);
-       device_total_in += packet->len;
-       ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Read packet of %d bytes from %s"), packet->len,
-                          device_info);
-       return true;
+       return false;
  }
  
 -bool write_packet(vpn_packet_t *packet)
 -{
 -      long lenout;
 +bool write_packet(vpn_packet_t *packet) {
 +      long outlen;
        OVERLAPPED overlapped = {0};
  
        cp();
diff --cc src/net.h
Simple merge
index 8bf41c39405b62d2c1e6e78898d04e5908e81346,aca84683e5aaa5a500758803bdcaf90ba435ac8e..77e29c0a9deeda77080d1208ec7edbadc4324c2c
@@@ -64,7 -68,13 +64,12 @@@ static void send_mtu_probe_handler(int 
        cp();
  
        n->mtuprobes++;
 -      n->mtuevent = NULL;
  
+       if(!n->status.reachable) {
+               logger(LOG_DEBUG, _("Trying to send MTU probe to unreachable node %s (%s)"), n->name, n->hostname);
+               return;
+       }
        if(n->mtuprobes >= 10 && !n->minmtu) {
                ifdebug(TRAFFIC) logger(LOG_INFO, _("No response to MTU probes from %s (%s)"), n->name, n->hostname);
                return;
diff --cc src/net_setup.c
index 224bdf6113f335dde59d19148005c9aaffe93f7b,3c4bf48c71607795b8c5f4bedbc44436ef2e1991..623eb1856692507628971263529110e5ff244cc4
@@@ -105,10 -170,8 +105,10 @@@ bool read_rsa_private_key() 
                return true;
        }
  
 +      /* Else, check for PrivateKeyFile statement and read it */
 +
        if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
-               asprintf(&fname, "%s/rsa_key.priv", confbase);
+               xasprintf(&fname, "%s/rsa_key.priv", confbase);
  
        fp = fopen(fname, "r");
  
@@@ -296,36 -349,65 +299,36 @@@ bool setup_myself(void) 
  
        /* Generate packet encryption key */
  
 -      if(get_config_string
 -         (lookup_config(myself->connection->config_tree, "Cipher"), &cipher)) {
 -              if(!strcasecmp(cipher, "none")) {
 -                      myself->incipher = NULL;
 -              } else {
 -                      myself->incipher = EVP_get_cipherbyname(cipher);
 -
 -                      if(!myself->incipher) {
 -                              logger(LOG_ERR, _("Unrecognized cipher type!"));
 -                              return false;
 -                      }
 -              }
 -      } else
 -              myself->incipher = EVP_aes_256_cbc();
 +      if(!get_config_string(lookup_config(myself->connection->config_tree, "Cipher"), &cipher))
-               cipher = xstrdup("blowfish");
++              cipher = xstrdup("aes256");
  
 -      if(myself->incipher)
 -              myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
 -      else
 -              myself->inkeylength = 1;
 -
 -      myself->connection->outcipher = EVP_aes_256_ofb();
 +      if(!cipher_open_by_name(&myself->incipher, cipher)) {
 +              logger(LOG_ERR, _("Unrecognized cipher type!"));
 +              return false;
 +      }
  
        if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
                keylifetime = 3600;
  
 -      keyexpires = now + keylifetime;
 -      
 +      regenerate_key();
 +
        /* Check if we want to use message authentication codes... */
  
 -      if(get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest)) {
 -              if(!strcasecmp(digest, "none")) {
 -                      myself->indigest = NULL;
 -              } else {
 -                      myself->indigest = EVP_get_digestbyname(digest);
 +      if(!get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest))
-               digest = xstrdup("sha1");
++              digest = xstrdup("sha256");
  
 -                      if(!myself->indigest) {
 -                              logger(LOG_ERR, _("Unrecognized digest type!"));
 -                              return false;
 -                      }
 -              }
 -      } else
 -              myself->indigest = EVP_sha256();
 -
 -      myself->connection->outdigest = EVP_sha256();
 -
 -      if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->inmaclength)) {
 -              if(myself->indigest) {
 -                      if(myself->inmaclength > myself->indigest->md_size) {
 -                              logger(LOG_ERR, _("MAC length exceeds size of digest!"));
 -                              return false;
 -                      } else if(myself->inmaclength < 0) {
 -                              logger(LOG_ERR, _("Bogus MAC length!"));
 -                              return false;
 -                      }
 -              }
 -      } else
 -              myself->inmaclength = 4;
 +      int maclength = 4;
 +      get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &maclength);
  
 -      myself->connection->outmaclength = 0;
 +      if(maclength < 0) {
 +              logger(LOG_ERR, _("Bogus MAC length!"));
 +              return false;
 +      }
 +
 +      if(!digest_open_by_name(&myself->indigest, digest, maclength)) {
 +              logger(LOG_ERR, _("Unrecognized digest type!"));
 +              return false;
 +      }
  
        /* Compression */
  
        if(!setup_device())
                return false;
  
 +      event_set(&device_ev, device_fd, EV_READ|EV_PERSIST, handle_device_data, NULL);
 +
 +      if (event_add(&device_ev, NULL) < 0) {
 +              logger(LOG_ERR, _("event_add failed: %s"), strerror(errno));
 +              close_device();
 +              return false;
 +      }
 +
        /* Run tinc-up script to further initialize the tap interface */
-       asprintf(&envp[0], "NETNAME=%s", netname ? : "");
-       asprintf(&envp[1], "DEVICE=%s", device ? : "");
-       asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
-       asprintf(&envp[3], "NAME=%s", myself->name);
+       xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
+       xasprintf(&envp[1], "DEVICE=%s", device ? : "");
+       xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
+       xasprintf(&envp[3], "NAME=%s", myself->name);
        envp[4] = NULL;
  
        execute_script("tinc-up", envp);
Simple merge
diff --cc src/netutl.c
Simple merge
diff --cc src/node.c
index 6df236a1a76681ffa5cf1ce8ef47b775acac7625,4fbec08fabcb8e1a18e8588f089661b3832f5a01..ebd2c7c2c9421d56c1225c89c95f7d593189c278
@@@ -131,11 -137,12 +131,11 @@@ void node_del(node_t *n) 
                edge_del(e);
        }
  
-       splay_delete(node_tree, n);
 -      avl_delete(node_udp_tree, n);
 -      avl_delete(node_tree, n);
 +      splay_delete(node_udp_tree, n);
++      splay_delete(node_tree, n);
  }
  
 -node_t *lookup_node(char *name)
 -{
 +node_t *lookup_node(char *name) {
        node_t n = {0};
  
        cp();
@@@ -166,12 -174,12 +166,12 @@@ void update_node_udp(node_t *n, const s
        if(sa) {
                n->address = *sa;
                n->hostname = sockaddr2hostname(&n->address);
-               splay_delete(node_udp_tree, n);
 -              avl_insert(node_udp_tree, n);
 -              ifdebug(PROTOCOL) logger(LOG_DEBUG, "UDP address of %s set to %s", n->name, n->hostname);
 +              splay_insert(node_udp_tree, n);
 +              logger(LOG_DEBUG, "UDP address of %s set to %s", n->name, n->hostname);
        } else {
                memset(&n->address, 0, sizeof n->address);
-               logger(LOG_DEBUG, "UDP address of %s cleared", n->name);
+               n->hostname = 0;
+               ifdebug(PROTOCOL) logger(LOG_DEBUG, "UDP address of %s cleared", n->name);
        }
  }
  
@@@ -181,15 -190,16 +181,15 @@@ int dump_nodes(struct evbuffer *out) 
  
        cp();
  
 -      logger(LOG_DEBUG, _("Nodes:"));
 -
        for(node = node_tree->head; node; node = node->next) {
                n = node->data;
 -              logger(LOG_DEBUG, _(" %s at %s cipher %d digest %d maclength %d compression %d options %lx status %04x nexthop %s via %s pmtu %d (min %d max %d)"),
 -                         n->name, n->hostname, n->outcipher ? n->outcipher->nid : 0,
 -                         n->outdigest ? n->outdigest->type : 0, n->outmaclength, n->outcompression,
 +              if(evbuffer_add_printf(out, _(" %s at %s cipher %d digest %d maclength %d compression %d options %lx status %04x nexthop %s via %s distance %d pmtu %d (min %d max %d)\n"),
 +                         n->name, n->hostname, cipher_get_nid(&n->outcipher),
 +                         digest_get_nid(&n->outdigest), digest_length(&n->outdigest), n->outcompression,
-                          n->options, *(uint32_t *)&n->status, n->nexthop ? n->nexthop->name : "-",
+                          n->options, bitfield_to_int(&n->status, sizeof n->status), n->nexthop ? n->nexthop->name : "-",
 -                         n->via ? n->via->name : "-", n->mtu, n->minmtu, n->maxmtu);
 +                         n->via ? n->via->name : "-", n->distance, n->mtu, n->minmtu, n->maxmtu) == -1)
 +                      return errno;
        }
  
 -      logger(LOG_DEBUG, _("End of nodes."));
 +      return 0;
  }
diff --cc src/node.h
Simple merge
diff --cc src/process.c
index 29cd486d76c0d543815fa317bd62d775676ce745,544c2242fcce5bec1c845b520ba0bbf889ea809b..546570aa59f4dc3066ff1b26cfbd99ea646fe661
@@@ -258,10 -360,10 +258,9 @@@ bool detach(void) 
        return true;
  }
  
 -bool execute_script(const char *name, char **envp)
 -{
 +bool execute_script(const char *name, char **envp) {
  #ifdef HAVE_SYSTEM
        int status, len;
-       struct stat s;
        char *scriptname, *p;
        int i;
  
diff --cc src/protocol.c
Simple merge
index 35776116ee929c0cf33fcffd8bd29910c9b28d2d,4066a30db18e359438e73d1edc95f45b9690078b..92d31dbdd889cf35624ac7c28d9ad5f25da4eea0
@@@ -172,10 -174,11 +172,10 @@@ bool add_edge_h(connection_t *c, char *
        return true;
  }
  
 -bool send_del_edge(connection_t *c, const edge_t *e)
 -{
 +bool send_del_edge(connection_t *c, const edge_t *e) {
        cp();
  
-       return send_request(c, "%d %lx %s %s", DEL_EDGE, random(),
+       return send_request(c, "%d %x %s %s", DEL_EDGE, rand(),
                                                e->from->name, e->to->name);
  }
  
index 2a0f2301d98babf2632ffa9d76f8ce8b75a97c55,7ae98036a26036e82bd4a9f4ce5b13dbd008fa97..60e9d73691b7c6993effaf99ca317bcadf11a3a4
@@@ -46,10 -49,11 +46,10 @@@ bool send_key_changed() 
        if(!mykeyused)
                return true;
  
-       return send_request(broadcast, "%d %lx %s", KEY_CHANGED, random(), myself->name);
+       return send_request(broadcast, "%d %x %s", KEY_CHANGED, rand(), myself->name);
  }
  
 -bool key_changed_h(connection_t *c)
 -{
 +bool key_changed_h(connection_t *c, char *request) {
        char name[MAX_STRING_SIZE];
        node_t *n;
  
index 02e3859810d2d9f76880abca5be513d852666767,18ff13c8de4bfb05a101666af22f2246f209d1a2..b8d2f67d39c6158484b89bc1ae91686c3faeaca8
@@@ -154,7 -158,7 +154,7 @@@ bool send_tcppacket(connection_t *c, vp
        /* If there already is a lot of data in the outbuf buffer, discard this packet.
             We use a very simple Random Early Drop algorithm. */
  
-       if(2.0 * c->buffer->output->off / (double)maxoutbufsize - 1 > drand48())
 -      if(2.0 * c->outbuflen / (float)maxoutbufsize - 1 > (float)rand()/(float)RAND_MAX)
++      if(2.0 * c->buffer->output->off / (float)maxoutbufsize - 1 > (float)rand()/(float)RAND_MAX)
                return true;
  
        if(!send_request(c, "%d %hd", PACKET, packet->len))
index e5927213e379f04096fc26d1c4806c0e63d543d8,b50cf6a348cd4d0367902f615d3df57e5b576552..9c5b04c8866dca45a73ac6b5efe19380c677f63b
@@@ -42,10 -42,10 +42,10 @@@ bool send_add_subnet(connection_t *c, c
        if(!net2str(netstr, sizeof netstr, subnet))
                return false;
  
-       return send_request(c, "%d %lx %s %s", ADD_SUBNET, random(), subnet->owner->name, netstr);
+       return send_request(c, "%d %x %s %s", ADD_SUBNET, rand(), subnet->owner->name, netstr);
  }
  
 -bool add_subnet_h(connection_t *c)
 +bool add_subnet_h(connection_t *c, char *request)
  {
        char subnetstr[MAX_STRING_SIZE];
        char name[MAX_STRING_SIZE];
@@@ -161,10 -161,10 +161,10 @@@ bool send_del_subnet(connection_t *c, c
        if(!net2str(netstr, sizeof netstr, s))
                return false;
  
-       return send_request(c, "%d %lx %s %s", DEL_SUBNET, random(), s->owner->name, netstr);
+       return send_request(c, "%d %x %s %s", DEL_SUBNET, rand(), s->owner->name, netstr);
  }
  
 -bool del_subnet_h(connection_t *c)
 +bool del_subnet_h(connection_t *c, char *request)
  {
        char subnetstr[MAX_STRING_SIZE];
        char name[MAX_STRING_SIZE];
diff --cc src/route.c
index 8acabb1b02999b931ca5fb607e1a7335c10ef25b,9b689039c17250f2a57b2c9c44a37132783f478c..da37473ca930ed64a26c517248ab7f12f0f820b4
@@@ -97,44 -94,14 +97,51 @@@ static bool checklength(node_t *source
        } else
                return true;
  }
+ static void swap_mac_addresses(vpn_packet_t *packet) {
+       mac_t tmp;
+       memcpy(&tmp, &packet->data[0], sizeof tmp);
+       memcpy(&packet->data[0], &packet->data[6], sizeof tmp);
+       memcpy(&packet->data[6], &tmp, sizeof tmp);
+ }
        
 +static void age_subnets(int fd, short events, void *data)
 +{
 +      subnet_t *s;
 +      connection_t *c;
 +      splay_node_t *node, *next, *node2;
 +      bool left = false;
 +      time_t now = time(NULL);
 +
 +      cp();
 +
 +      for(node = myself->subnet_tree->head; node; node = next) {
 +              next = node->next;
 +              s = node->data;
 +              if(s->expires && s->expires < now) {
 +                      ifdebug(TRAFFIC) {
 +                              char netstr[MAXNETSTR];
 +                              if(net2str(netstr, sizeof netstr, s))
 +                                      logger(LOG_INFO, _("Subnet %s expired"), netstr);
 +                      }
 +
 +                      for(node2 = connection_tree->head; node2; node2 = node2->next) {
 +                              c = node2->data;
 +                              if(c->status.active)
 +                                      send_del_subnet(c, s);
 +                      }
 +
 +                      subnet_del(myself, s);
 +              } else {
 +                      if(s->expires)
 +                              left = true;
 +              }
 +      }
 +
 +      if(left)
 +              event_add(&age_subnets_event, &(struct timeval){10, 0});
 +}
 +
  static void learn_mac(mac_t *address)
  {
        subnet_t *subnet;
Simple merge
diff --cc src/subnet.c
index 75fe31f886237c40bafc3f65a2518a0f884edc5d,140b61450f0f5a836c83bfbd1084552256a5c37c..057550ab0760455f1626aaedebb49aed970f9c9a
@@@ -474,16 -474,19 +474,19 @@@ subnet_t *lookup_subnet_ipv6(const ipv6
  }
  
  void subnet_update(node_t *owner, subnet_t *subnet, bool up) {
 -      avl_node_t *node;
 +      splay_node_t *node;
        int i;
-       char *envp[8];
-       char netstr[MAXNETSTR + 7] = "SUBNET=";
+       char *envp[9] = {0};
+       char netstr[MAXNETSTR];
        char *name, *address, *port;
+       char empty[] = "";
+       // Prepare environment variables to be passed to the script
  
-       asprintf(&envp[0], "NETNAME=%s", netname ? : "");
-       asprintf(&envp[1], "DEVICE=%s", device ? : "");
-       asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
-       asprintf(&envp[3], "NODE=%s", owner->name);
+       xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
+       xasprintf(&envp[1], "DEVICE=%s", device ? : "");
+       xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
+       xasprintf(&envp[3], "NODE=%s", owner->name);
  
        if(owner != myself) {
                sockaddr2str(&owner->address, &address, &port);
                        execute_script(name, envp);
                }
        } else {
-               if(net2str(netstr + 7, sizeof netstr - 7, subnet))
+               if(net2str(netstr + 7, sizeof netstr - 7, subnet)) {
+                       // Strip the weight from the subnet, and put it in its own environment variable
+                       char *weight = strchr(netstr + 7, '#');
+                       if(weight)
+                               *weight++ = 0;
+                       else
+                               weight = empty;
+                       // Prepare the SUBNET and WEIGHT variables
+                       xasprintf(&envp[4], "SUBNET=%s", netstr);
+                       xasprintf(&envp[5], "WEIGHT=%s", weight);
                        execute_script(name, envp);
+               }
        }
  
-       for(i = 0; i < (owner != myself ? 6 : 4); i++)
+       for(i = 0; envp[i] && i < 9; i++)
                free(envp[i]);
-       if(owner != myself) {
-               free(address);
-               free(port);
-       }
  }
  
 -void dump_subnets(void)
 +int dump_subnets(struct evbuffer *out)
  {
        char netstr[MAXNETSTR];
        subnet_t *subnet;
diff --cc src/tincctl.c
index 814800e8969c6c62c7060f26786789ef8fb63671,0000000000000000000000000000000000000000..92796b6bea42ed7b52e7f99d3625f2c4acacf4e7
mode 100644,000000..100644
--- /dev/null
@@@ -1,591 -1,0 +1,591 @@@
-               return !keygen(optind > argc ? atoi(argv[optind + 1]) : 1024);
 +/*
 +    tincctl.c -- Controlling a running tincd
 +    Copyright (C) 2007 Guus Sliepen <guus@tinc-vpn.org>
 +
 +    This program is free software; you can redistribute it and/or modify
 +    it under the terms of the GNU General Public License as published by
 +    the Free Software Foundation; either version 2 of the License, or
 +    (at your option) any later version.
 +
 +    This program is distributed in the hope that it will be useful,
 +    but WITHOUT ANY WARRANTY; without even the implied warranty of
 +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 +    GNU General Public License for more details.
 +
 +    You should have received a copy of the GNU General Public License
 +    along with this program; if not, write to the Free Software
 +    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 +
 +    $Id$
 +*/
 +
 +#include "system.h"
 +
 +#include <sys/un.h>
 +#include <getopt.h>
 +
 +#include "xalloc.h"
 +#include "protocol.h"
 +#include "control_common.h"
 +#include "rsagen.h"
 +
 +/* The name this program was run with. */
 +char *program_name = NULL;
 +
 +/* If nonzero, display usage information and exit. */
 +bool show_help = false;
 +
 +/* If nonzero, print the version on standard output and exit.  */
 +bool show_version = false;
 +
 +/* If nonzero, it will attempt to kill a running tincd and exit. */
 +int kill_tincd = 0;
 +
 +/* If nonzero, generate public/private keypair for this host/net. */
 +int generate_keys = 0;
 +
 +static char *identname = NULL;                                /* program name for syslog */
 +static char *controlsocketname = NULL;                        /* pid file location */
 +char *netname = NULL;
 +char *confbase = NULL;
 +
 +static struct option const long_options[] = {
 +      {"config", required_argument, NULL, 'c'},
 +      {"net", required_argument, NULL, 'n'},
 +      {"help", no_argument, NULL, 1},
 +      {"version", no_argument, NULL, 2},
 +      {"controlsocket", required_argument, NULL, 5},
 +      {NULL, 0, NULL, 0}
 +};
 +
 +static void usage(bool status) {
 +      if(status)
 +              fprintf(stderr, _("Try `%s --help\' for more information.\n"),
 +                              program_name);
 +      else {
 +              printf(_("Usage: %s [options] command\n\n"), program_name);
 +              printf(_("Valid options are:\n"
 +                              "  -c, --config=DIR              Read configuration options from DIR.\n"
 +                              "  -n, --net=NETNAME             Connect to net NETNAME.\n"
 +                              "      --controlsocket=FILENAME  Open control socket at FILENAME.\n"
 +                              "      --help                    Display this help and exit.\n"
 +                              "      --version                 Output version information and exit.\n"
 +                              "\n"
 +                              "Valid commands are:\n"
 +                              "  start                      Start tincd.\n"
 +                              "  stop                       Stop tincd.\n"
 +                              "  restart                    Restart tincd.\n"
 +                              "  reload                     Reload configuration of running tincd.\n"
 +                              "  pid                        Show PID of currently running tincd.\n"
 +                              "  generate-keys [bits]       Generate a new public/private keypair.\n"
 +                              "  dump                       Dump a list of one of the following things:\n"
 +                              "    nodes                    - all known nodes in the VPN\n"
 +                              "    edges                    - all known connections in the VPN\n"
 +                              "    subnets                  - all known subnets in the VPN\n"
 +                              "    connections              - all meta connections with ourself\n"
 +                              "    graph                    - graph of the VPN in dotty format\n"
 +                              "  purge                      Purge unreachable nodes\n"
 +                              "  debug N                    Set debug level\n"
 +                              "  retry                      Retry all outgoing connections\n"
 +                              "  reload                     Partial reload of configuration\n"
 +                              "\n"));
 +              printf(_("Report bugs to tinc@tinc-vpn.org.\n"));
 +      }
 +}
 +
 +static bool parse_options(int argc, char **argv) {
 +      int r;
 +      int option_index = 0;
 +
 +      while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
 +              switch (r) {
 +                      case 0:                         /* long option */
 +                              break;
 +
 +                      case 'c':                               /* config file */
 +                              confbase = xstrdup(optarg);
 +                              break;
 +
 +                      case 'n':                               /* net name given */
 +                              netname = xstrdup(optarg);
 +                              break;
 +
 +                      case 1:                                 /* show help */
 +                              show_help = true;
 +                              break;
 +
 +                      case 2:                                 /* show version */
 +                              show_version = true;
 +                              break;
 +
 +                      case 5:                                 /* open control socket here */
 +                              controlsocketname = xstrdup(optarg);
 +                              break;
 +
 +                      case '?':
 +                              usage(true);
 +                              return false;
 +
 +                      default:
 +                              break;
 +              }
 +      }
 +
 +      return true;
 +}
 +
 +FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
 +      FILE *r;
 +      char *directory;
 +      char buf[PATH_MAX];
 +      char buf2[PATH_MAX];
 +      size_t len;
 +
 +      /* Check stdin and stdout */
 +      if(isatty(0) && isatty(1)) {
 +              /* Ask for a file and/or directory name. */
 +              fprintf(stdout, _("Please enter a file to save %s to [%s]: "),
 +                              what, filename);
 +              fflush(stdout);
 +
 +              if(fgets(buf, sizeof buf, stdin) < 0) {
 +                      fprintf(stderr, _("Error while reading stdin: %s\n"),
 +                                      strerror(errno));
 +                      return NULL;
 +              }
 +
 +              len = strlen(buf);
 +              if(len)
 +                      buf[--len] = 0;
 +
 +              if(len)
 +                      filename = buf;
 +      }
 +
 +#ifdef HAVE_MINGW
 +      if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
 +#else
 +      if(filename[0] != '/') {
 +#endif
 +              /* The directory is a relative path or a filename. */
 +              directory = get_current_dir_name();
 +              snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
 +              filename = buf2;
 +      }
 +
 +      umask(0077);                            /* Disallow everything for group and other */
 +
 +      /* Open it first to keep the inode busy */
 +
 +      r = fopen(filename, mode);
 +
 +      if(!r) {
 +              fprintf(stderr, _("Error opening file `%s': %s\n"), filename, strerror(errno));
 +              return NULL;
 +      }
 +
 +      return r;
 +}
 +
 +/*
 +  Generate a public/private RSA keypair, and ask for a file to store
 +  them in.
 +*/
 +static bool keygen(int bits) {
 +      rsa_t key;
 +      FILE *f;
 +      char *name = NULL;
 +      char *filename;
 +
 +      fprintf(stderr, _("Generating %d bits keys:\n"), bits);
 +
 +      if(!rsa_generate(&key, bits, 0x10001)) {
 +              fprintf(stderr, _("Error during key generation!\n"));
 +              return false;
 +      } else
 +              fprintf(stderr, _("Done.\n"));
 +
 +      asprintf(&filename, "%s/rsa_key.priv", confbase);
 +      f = ask_and_open(filename, _("private RSA key"), "a");
 +
 +      if(!f)
 +              return false;
 +  
 +#ifdef HAVE_FCHMOD
 +      /* Make it unreadable for others. */
 +      fchmod(fileno(f), 0600);
 +#endif
 +              
 +      if(ftell(f))
 +              fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
 +
 +      rsa_write_pem_private_key(&key, f);
 +
 +      fclose(f);
 +      free(filename);
 +
 +      if(name)
 +              asprintf(&filename, "%s/hosts/%s", confbase, name);
 +      else
 +              asprintf(&filename, "%s/rsa_key.pub", confbase);
 +
 +      f = ask_and_open(filename, _("public RSA key"), "a");
 +
 +      if(!f)
 +              return false;
 +
 +      if(ftell(f))
 +              fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
 +
 +      rsa_write_pem_public_key(&key, f);
 +
 +      fclose(f);
 +      free(filename);
 +
 +      return true;
 +}
 +
 +/*
 +  Set all files and paths according to netname
 +*/
 +static void make_names(void) {
 +#ifdef HAVE_MINGW
 +      HKEY key;
 +      char installdir[1024] = "";
 +      long len = sizeof installdir;
 +#endif
 +
 +      if(netname)
 +              asprintf(&identname, "tinc.%s", netname);
 +      else
 +              identname = xstrdup("tinc");
 +
 +#ifdef HAVE_MINGW
 +      if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
 +              if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
 +                      if(!logfilename)
 +                              asprintf(&logfilename, "%s/log/%s.log", identname);
 +                      if(!confbase) {
 +                              if(netname)
 +                                      asprintf(&confbase, "%s/%s", installdir, netname);
 +                              else
 +                                      asprintf(&confbase, "%s", installdir);
 +                      }
 +              }
 +              RegCloseKey(key);
 +              if(*installdir)
 +                      return;
 +      }
 +#endif
 +
 +      if(!controlsocketname)
 +              asprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname);
 +
 +      if(netname) {
 +              if(!confbase)
 +                      asprintf(&confbase, CONFDIR "/tinc/%s", netname);
 +              else
 +                      fprintf(stderr, _("Both netname and configuration directory given, using the latter...\n"));
 +      } else {
 +              if(!confbase)
 +                      asprintf(&confbase, CONFDIR "/tinc");
 +      }
 +}
 +
 +static int fullread(int fd, void *data, size_t datalen) {
 +      int rv, len = 0;
 +
 +      while(len < datalen) {
 +              rv = read(fd, data + len, datalen - len);
 +              if(rv == -1 && errno == EINTR)
 +                      continue;
 +              else if(rv == -1)
 +                      return rv;
 +              else if(rv == 0) {
 +                      errno = ENODATA;
 +                      return -1;
 +              }
 +              len += rv;
 +      }
 +      return 0;
 +}
 +
 +/*
 +   Send a request (raw)
 +*/
 +static int send_ctl_request(int fd, enum request_type type,
 +                                                 void const *outdata, size_t outdatalen,
 +                                                 int *res_errno_p, void **indata_p,
 +                                                 size_t *indatalen_p) {
 +      tinc_ctl_request_t req;
 +      int rv;
 +      struct iovec vector[2] = {
 +              {&req, sizeof req},
 +              {(void*) outdata, outdatalen}
 +      };
 +      void *indata;
 +
 +      if(res_errno_p == NULL)
 +              return -1;
 +
 +      memset(&req, 0, sizeof req);
 +      req.length = sizeof req + outdatalen;
 +      req.type = type;
 +      req.res_errno = 0;
 +
 +      while((rv = writev(fd, vector, 2)) == -1 && errno == EINTR) ;
 +      if(rv != req.length)
 +              return -1;
 +
 +      if(fullread(fd, &req, sizeof req) == -1)
 +              return -1;
 +
 +      if(req.length < sizeof req) {
 +              errno = EINVAL;
 +              return -1;
 +      }
 +
 +      if(req.length > sizeof req) {
 +              if(indata_p == NULL) {
 +                      errno = EINVAL;
 +                      return -1;
 +              }
 +
 +              indata = xmalloc(req.length - sizeof req);
 +
 +              if(fullread(fd, indata, req.length - sizeof req) == -1) {
 +                      free(indata);
 +                      return -1;
 +              }
 +
 +              *indata_p = indata;
 +              if(indatalen_p != NULL)
 +                      *indatalen_p = req.length - sizeof req;
 +      }
 +
 +      *res_errno_p = req.res_errno;
 +
 +      return 0;
 +}
 +
 +/*
 +   Send a request (with printfs)
 +*/
 +static int send_ctl_request_cooked(int fd, enum request_type type,
 +                                                                 void const *outdata, size_t outdatalen)
 +{
 +      int res_errno = -1;
 +      char *buf = NULL;
 +      size_t buflen = 0;
 +
 +      if(send_ctl_request(fd, type, outdata, outdatalen, &res_errno,
 +                                              (void**) &buf, &buflen)) {
 +              fprintf(stderr, _("Error sending request: %s\n"), strerror(errno));
 +              return -1;
 +      }
 +
 +      if(buf != NULL) {
 +              printf("%*s", (int)buflen, buf);
 +              free(buf);
 +      }
 +
 +      if(res_errno != 0) {
 +              fprintf(stderr, _("Server reported error: %s\n"), strerror(res_errno));
 +              return -1;
 +      }
 +
 +      return 0;
 +}
 +
 +int main(int argc, char *argv[], char *envp[]) {
 +      struct sockaddr_un addr;
 +      tinc_ctl_greeting_t greeting;
 +      int fd;
 +      int result;
 +
 +      program_name = argv[0];
 +
 +      setlocale(LC_ALL, "");
 +      bindtextdomain(PACKAGE, LOCALEDIR);
 +      textdomain(PACKAGE);
 +
 +      if(!parse_options(argc, argv))
 +              return 1;
 +      
 +      make_names();
 +
 +      if(show_version) {
 +              printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
 +                         VERSION, __DATE__, __TIME__, PROT_CURRENT);
 +              printf(_("Copyright (C) 1998-2007 Ivo Timmermans, Guus Sliepen and others.\n"
 +                              "See the AUTHORS file for a complete list.\n\n"
 +                              "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
 +                              "and you are welcome to redistribute it under certain conditions;\n"
 +                              "see the file COPYING for details.\n"));
 +
 +              return 0;
 +      }
 +
 +      if(show_help) {
 +              usage(false);
 +              return 0;
 +      }
 +
 +      if(optind >= argc) {
 +              fprintf(stderr, _("Not enough arguments.\n"));
 +              usage(true);
 +              return 1;
 +      }
 +
 +      // First handle commands that don't involve connecting to a running tinc daemon.
 +
 +      if(!strcasecmp(argv[optind], "generate-keys")) {
++              return !keygen(optind > argc ? atoi(argv[optind + 1]) : 2048);
 +      }
 +
 +      if(!strcasecmp(argv[optind], "start")) {
 +              argv[optind] = NULL;
 +              execve(SBINDIR "/tincd", argv, envp);
 +              fprintf(stderr, _("Could not start tincd: %s"), strerror(errno));
 +              return 1;
 +      }
 +
 +      /*
 +       * Now handle commands that do involve connecting to a running tinc daemon.
 +       * Authenticate the server by ensuring the parent directory can be
 +       * traversed only by root. Note this is not totally race-free unless all
 +       * ancestors are writable only by trusted users, which we don't verify.
 +       */
 +
 +      struct stat statbuf;
 +      char *lastslash = strrchr(controlsocketname, '/');
 +      if(lastslash != NULL) {
 +              /* control socket is not in cwd; stat its parent */
 +              *lastslash = 0;
 +              result = stat(controlsocketname, &statbuf);
 +              *lastslash = '/';
 +      } else
 +              result = stat(".", &statbuf);
 +
 +      if(result < 0) {
 +              fprintf(stderr, _("Unable to check control socket directory permissions: %s\n"), strerror(errno));
 +              return 1;
 +      }
 +
 +      if(statbuf.st_uid != 0 || (statbuf.st_mode & S_IXOTH) != 0 || (statbuf.st_gid != 0 && (statbuf.st_mode & S_IXGRP)) != 0) {
 +              fprintf(stderr, _("Insecure permissions on control socket directory\n"));
 +              return 1;
 +      }
 +
 +      if(strlen(controlsocketname) >= sizeof addr.sun_path) {
 +              fprintf(stderr, _("Control socket filename too long!\n"));
 +              return 1;
 +      }
 +
 +      fd = socket(PF_UNIX, SOCK_STREAM, 0);
 +      if(fd < 0) {
 +              fprintf(stderr, _("Cannot create UNIX socket: %s\n"), strerror(errno));
 +              return 1;
 +      }
 +
 +      memset(&addr, 0, sizeof addr);
 +      addr.sun_family = AF_UNIX;
 +      strncpy(addr.sun_path, controlsocketname, sizeof addr.sun_path - 1);
 +
 +      if(connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
 +              fprintf(stderr, _("Cannot connect to %s: %s\n"), controlsocketname, strerror(errno));
 +              return 1;
 +      }
 +
 +      if(fullread(fd, &greeting, sizeof greeting) == -1) {
 +              fprintf(stderr, _("Cannot read greeting from control socket: %s\n"),
 +                              strerror(errno));
 +              return 1;
 +      }
 +
 +      if(greeting.version != TINC_CTL_VERSION_CURRENT) {
 +              fprintf(stderr, _("Version mismatch: server %d, client %d\n"),
 +                              greeting.version, TINC_CTL_VERSION_CURRENT);
 +              return 1;
 +      }
 +
 +      if(!strcasecmp(argv[optind], "pid")) {
 +              printf("%d\n", greeting.pid);
 +              return 0;
 +      }
 +
 +      if(!strcasecmp(argv[optind], "stop")) {
 +              return send_ctl_request_cooked(fd, REQ_STOP, NULL, 0) != -1;
 +      }
 +
 +      if(!strcasecmp(argv[optind], "reload")) {
 +              return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
 +      }
 +      
 +      if(!strcasecmp(argv[optind], "restart")) {
 +              return send_ctl_request_cooked(fd, REQ_RESTART, NULL, 0) != -1;
 +      }
 +
 +      if(!strcasecmp(argv[optind], "dump")) {
 +              if(argc < optind + 2) {
 +                      fprintf(stderr, _("Not enough arguments.\n"));
 +                      usage(true);
 +                      return 1;
 +              }
 +
 +              if(!strcasecmp(argv[optind+1], "nodes")) {
 +                      return send_ctl_request_cooked(fd, REQ_DUMP_NODES, NULL, 0) != -1;
 +              }
 +
 +              if(!strcasecmp(argv[optind+1], "edges")) {
 +                      return send_ctl_request_cooked(fd, REQ_DUMP_EDGES, NULL, 0) != -1;
 +              }
 +
 +              if(!strcasecmp(argv[optind+1], "subnets")) {
 +                      return send_ctl_request_cooked(fd, REQ_DUMP_SUBNETS, NULL, 0) != -1;
 +              }
 +
 +              if(!strcasecmp(argv[optind+1], "connections")) {
 +                      return send_ctl_request_cooked(fd, REQ_DUMP_CONNECTIONS, NULL, 0) != -1;
 +              }
 +
 +              if(!strcasecmp(argv[optind+1], "graph")) {
 +                      return send_ctl_request_cooked(fd, REQ_DUMP_GRAPH, NULL, 0) != -1;
 +              }
 +
 +              fprintf(stderr, _("Unknown dump type '%s'.\n"), argv[optind+1]);
 +              usage(true);
 +              return 1;
 +      }
 +
 +      if(!strcasecmp(argv[optind], "purge")) {
 +              return send_ctl_request_cooked(fd, REQ_PURGE, NULL, 0) != -1;
 +      }
 +
 +      if(!strcasecmp(argv[optind], "debug")) {
 +              int debuglevel;
 +
 +              if(argc != optind + 2) {
 +                      fprintf(stderr, "Invalid arguments.\n");
 +                      return 1;
 +              }
 +              debuglevel = atoi(argv[optind+1]);
 +              return send_ctl_request_cooked(fd, REQ_SET_DEBUG, &debuglevel,
 +                                                                         sizeof debuglevel) != -1;
 +      }
 +
 +      if(!strcasecmp(argv[optind], "retry")) {
 +              return send_ctl_request_cooked(fd, REQ_RETRY, NULL, 0) != -1;
 +      }
 +
 +      if(!strcasecmp(argv[optind], "reload")) {
 +              return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
 +      }
 +
 +      fprintf(stderr, _("Unknown command `%s'.\n"), argv[optind]);
 +      usage(true);
 +      
 +      close(fd);
 +
 +      return 0;
 +}
diff --cc src/tincd.c
index 76053a00825e27c348739775abd1e19ad849220e,602f18b1ff99a0c7f6167e529f517393e47c0061..48f5faf88ce2dd987a18f84643dda8902a09f8cb
@@@ -240,11 -412,11 +241,11 @@@ static void make_names(void
        }
  #endif
  
 -      if(!pidfilename)
 -              xasprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
 +      if(!controlsocketname)
-               asprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname);
++              xasprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname);
  
        if(!logfilename)
-               asprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
+               xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
  
        if(netname) {
                if(!confbase)
Simple merge