]> git.meshlink.io Git - meshlink/blobdiff - src/meshlink.c
Add functions to get the amount of bytes in chanenl send and receive buffers.
[meshlink] / src / meshlink.c
index f6121a1ea67f589335f271a7b3edd39568ca8435..8ec207842c6732bee32b25914db502c1174863d5 100644 (file)
@@ -1,6 +1,6 @@
 /*
     meshlink.c -- Implementation of the MeshLink API.
-    Copyright (C) 2014, 2017 Guus Sliepen <guus@meshlink.io>
+    Copyright (C) 2014-2018 Guus Sliepen <guus@meshlink.io>
 
     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
@@ -37,6 +37,7 @@ typedef struct {
 #include "meshlink_internal.h"
 #include "netutl.h"
 #include "node.h"
+#include "submesh.h"
 #include "protocol.h"
 #include "route.h"
 #include "sockaddr.h"
@@ -53,12 +54,15 @@ __thread meshlink_errno_t meshlink_errno;
 meshlink_log_cb_t global_log_cb;
 meshlink_log_level_t global_log_level;
 
+typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
+
 //TODO: this can go away completely
 const var_t variables[] = {
        /* Server configuration */
        {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
        {"Name", VAR_SERVER},
        /* Host configuration */
+       {"SubMesh", VAR_HOST | VAR_SAFE},
        {"CanonicalAddress", VAR_HOST},
        {"Address", VAR_HOST | VAR_MULTIPLE},
        {"ECDSAPublicKey", VAR_HOST},
@@ -95,9 +99,8 @@ static int rstrip(char *value) {
        return len;
 }
 
-static void scan_for_hostname(const char *filename, char **hostname, char **port) {
+static void scan_for_canonical_address(const char *filename, char **hostname, char **port) {
        char line[4096];
-       bool canonical = false;
 
        if(!filename || (*hostname && *port)) {
                return;
@@ -141,21 +144,8 @@ static void scan_for_hostname(const char *filename, char **hostname, char **port
 
                if(!*port && !strcasecmp(line, "Port")) {
                        *port = xstrdup(q);
-               } else if(!canonical && !*hostname && !strcasecmp(line, "Address")) {
-                       // Check that the hostname is a symbolic name (it's not a numeric IPv4 or IPv6 address)
-                       if(!q[strspn(q, "0123456789.")] || strchr(q, ':')) {
-                               continue;
-                       }
-
-                       *hostname = xstrdup(q);
-
-                       if(*p) {
-                               free(*port);
-                               *port = xstrdup(p);
-                       }
                } else if(!strcasecmp(line, "CanonicalAddress")) {
                        *hostname = xstrdup(q);
-                       canonical = true;
 
                        if(*p) {
                                free(*port);
@@ -163,7 +153,7 @@ static void scan_for_hostname(const char *filename, char **hostname, char **port
                        }
                }
 
-               if(canonical && *hostname && *port) {
+               if(*hostname && *port) {
                        break;
                }
        }
@@ -217,10 +207,46 @@ static void set_timeout(int sock, int timeout) {
        setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
 }
 
+struct socket_in_netns_params {
+       int domain;
+       int type;
+       int protocol;
+       int netns;
+       int fd;
+};
+
+static void *socket_in_netns_thread(void *arg) {
+       struct socket_in_netns_params *params = arg;
+
+       if(setns(params->netns, CLONE_NEWNET) == -1) {
+               meshlink_errno = MESHLINK_EINVAL;
+       } else {
+               params->fd = socket(params->domain, params->type, params->protocol);
+       }
+
+       return NULL;
+}
+
+static int socket_in_netns(int domain, int type, int protocol, int netns) {
+       if(netns == -1) {
+               return socket(domain, type, protocol);
+       }
+
+       struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
+
+       pthread_t thr;
+
+       if(pthread_create(&thr, NULL, socket_in_netns_thread, &params) == 0) {
+               pthread_join(thr, NULL);
+       }
+
+       return params.fd;
+}
+
 // Find out what local address a socket would use if we connect to the given address.
 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
 // of both endpoints, but this will actually not send any UDP packet.
-static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
+static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
        struct addrinfo *rai = NULL;
        const struct addrinfo hint = {
                .ai_family = AF_UNSPEC,
@@ -232,7 +258,7 @@ static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
                return false;
        }
 
-       int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
+       int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
 
        if(sock == -1) {
                freeaddrinfo(rai);
@@ -240,6 +266,7 @@ static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
        }
 
        if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
+               closesocket(sock);
                freeaddrinfo(rai);
                return false;
        }
@@ -250,9 +277,12 @@ static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
        socklen_t sl = sizeof(sn);
 
        if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
+               closesocket(sock);
                return false;
        }
 
+       closesocket(sock);
+
        if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
                return false;
        }
@@ -277,7 +307,7 @@ char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int fami
                        continue;
                }
 
-               int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
+               int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
 
                if(s >= 0) {
                        set_timeout(s, 5000);
@@ -324,88 +354,199 @@ char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int fami
                hostname = NULL;
        }
 
-       // If there is no hostname, determine the address used for an outgoing connection.
        if(!hostname) {
-               char localaddr[NI_MAXHOST];
-               bool success = false;
+               meshlink_errno = MESHLINK_ERESOLV;
+       }
 
-               if(family == AF_INET) {
-                       success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr));
-               } else if(family == AF_INET6) {
-                       success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr));
-               }
+       return hostname;
+}
 
-               if(success) {
-                       hostname = xstrdup(localaddr);
-               }
+char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
+       (void)mesh;
+
+       // Determine address of the local interface used for outgoing connections.
+       char localaddr[NI_MAXHOST];
+       bool success = false;
+
+       if(family == AF_INET) {
+               success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
+       } else if(family == AF_INET6) {
+               success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
        }
 
-       if(!hostname) {
-               meshlink_errno = MESHLINK_ERESOLV;
+       if(!success) {
+               meshlink_errno = MESHLINK_ENETWORK;
+               return NULL;
        }
 
-       return hostname;
+       return xstrdup(localaddr);
+}
+
+void remove_duplicate_hostnames(char *host[], char *port[], int n) {
+       for(int i = 0; i < n; i++) {
+               if(!host[i]) {
+                       continue;
+               }
+
+               // Ignore duplicate hostnames
+               bool found = false;
+
+               for(int j = 0; j < i; j++) {
+                       if(!host[j]) {
+                               continue;
+                       }
+
+                       if(strcmp(host[i], host[j])) {
+                               continue;
+                       }
+
+                       if(strcmp(port[i], port[j])) {
+                               continue;
+                       }
+
+                       found = true;
+                       break;
+               }
+
+               if(found) {
+                       free(host[i]);
+                       free(port[i]);
+                       host[i] = NULL;
+                       port[i] = NULL;
+                       continue;
+               }
+       }
 }
 
 // This gets the hostname part for use in invitation URLs
-static char *get_my_hostname(meshlink_handle_t *mesh) {
-       char *hostname[2] = {NULL};
-       char *port = NULL;
+static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
+       char *hostname[4] = {NULL};
+       char *port[4] = {NULL};
        char *hostport = NULL;
-       char *name = mesh->self->name;
-       char filename[PATH_MAX] = "";
 
-       // Use first Address statement in own host config file
-       snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
-       scan_for_hostname(filename, &hostname[0], &port);
+       if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
+               flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
+       }
 
-       if(hostname[0]) {
-               goto done;
+       if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
+               flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
        }
 
-       hostname[0] = meshlink_get_external_address_for_family(mesh, AF_INET);
-       hostname[1] = meshlink_get_external_address_for_family(mesh, AF_INET6);
+       // Add local addresses if requested
+       if(flags & MESHLINK_INVITE_LOCAL) {
+               if(flags & MESHLINK_INVITE_IPV4) {
+                       hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
+               }
 
-       if(!hostname[0] && !hostname[1]) {
-               return NULL;
+               if(flags & MESHLINK_INVITE_IPV6) {
+                       hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
+               }
        }
 
-       if(hostname[0] && hostname[1] && !strcmp(hostname[0], hostname[1])) {
-               free(hostname[1]);
-               hostname[1] = NULL;
+       // Add public/canonical addresses if requested
+       if(flags & MESHLINK_INVITE_PUBLIC) {
+               // Try the CanonicalAddress first
+               char filename[PATH_MAX] = "";
+               snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
+               scan_for_canonical_address(filename, &hostname[2], &port[2]);
+
+               if(!hostname[2]) {
+                       if(flags & MESHLINK_INVITE_IPV4) {
+                               hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
+                       }
+
+                       if(flags & MESHLINK_INVITE_IPV6) {
+                               hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
+                       }
+               }
+       }
+
+       for(int i = 0; i < 4; i++) {
+               // Ensure we always have a port number
+               if(hostname[i] && !port[i]) {
+                       port[i] = xstrdup(mesh->myport);
+               }
        }
 
-       port = xstrdup(mesh->myport);
+       remove_duplicate_hostnames(hostname, port, 4);
+
+       if(!(flags & MESHLINK_INVITE_NUMERIC)) {
+               for(int i = 0; i < 4; i++) {
+                       if(!hostname[i]) {
+                               continue;
+                       }
+
+                       // Convert what we have to a sockaddr
+                       struct addrinfo *ai_in, *ai_out;
+                       struct addrinfo hint = {
+                               .ai_family = AF_UNSPEC,
+                               .ai_flags = AI_NUMERICSERV,
+                               .ai_socktype = SOCK_STREAM,
+                       };
+                       int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
+
+                       if(err || !ai_in) {
+                               continue;
+                       }
+
+                       // Convert it to a hostname
+                       char resolved_host[NI_MAXHOST];
+                       char resolved_port[NI_MAXSERV];
+                       err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
+
+                       if(err) {
+                               freeaddrinfo(ai_in);
+                               continue;
+                       }
+
+                       // Convert the hostname back to a sockaddr
+                       hint.ai_family = ai_in->ai_family;
+                       err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
 
-       for(int i = 0; i < 2; i++) {
-               if(hostname[i]) {
-                       char *tmphostport;
-                       xasprintf(&tmphostport, "%s %s", hostname[i], port);
-                       append_config_file(mesh, mesh->self->name, "Address", tmphostport);
-                       free(tmphostport);
+                       if(err || !ai_out) {
+                               freeaddrinfo(ai_in);
+                               continue;
+                       }
+
+                       // Check if it's still the same sockaddr
+                       if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
+                               freeaddrinfo(ai_in);
+                               freeaddrinfo(ai_out);
+                               continue;
+                       }
+
+                       // Yes: replace the hostname with the resolved one
+                       free(hostname[i]);
+                       hostname[i] = xstrdup(resolved_host);
+
+                       freeaddrinfo(ai_in);
+                       freeaddrinfo(ai_out);
                }
        }
 
-done:
+       // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
+       remove_duplicate_hostnames(hostname, port, 4);
 
-       for(int i = 0; i < 2; i++) {
+       // Concatenate all unique address to the hostport string
+       for(int i = 0; i < 4; i++) {
                if(!hostname[i]) {
                        continue;
                }
 
-               char *newhostport;
-               xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]" : "%s%s%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i]);
-               free(hostname[i]);
-               free(hostport);
-               hostport = newhostport;
-       }
+               // Ensure we have the same addresses in our own host config file.
+               char *tmphostport;
+               xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
+               append_config_file(mesh, mesh->self->name, "Address", tmphostport);
+               free(tmphostport);
 
-       if(port) {
+               // Append the address to the hostport string
                char *newhostport;
-               xasprintf(&newhostport, "%s:%s", hostport, port);
-               free(port);
+               xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
                free(hostport);
                hostport = newhostport;
+
+               free(hostname[i]);
+               free(port[i]);
        }
 
        return hostport;
@@ -485,23 +626,22 @@ static bool try_bind(int port) {
                return false;
        }
 
-       while(ai) {
-               int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
+       //while(ai) {
+       for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
+               int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
 
                if(!fd) {
                        freeaddrinfo(ai);
                        return false;
                }
 
-               int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
+               int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
                closesocket(fd);
 
                if(result) {
                        freeaddrinfo(ai);
                        return false;
                }
-
-               ai = ai->ai_next;
        }
 
        freeaddrinfo(ai);
@@ -534,6 +674,31 @@ int check_port(meshlink_handle_t *mesh) {
        return 0;
 }
 
+static void deltree(const char *dirname) {
+       DIR *d = opendir(dirname);
+
+       if(d) {
+               struct dirent *ent;
+
+               while((ent = readdir(d))) {
+                       if(ent->d_name[0] == '.') {
+                               continue;
+                       }
+
+                       char filename[PATH_MAX];
+                       snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
+
+                       if(unlink(filename)) {
+                               deltree(filename);
+                       }
+               }
+
+               closedir(d);
+       }
+
+       rmdir(dirname);
+}
+
 static bool finalize_join(meshlink_handle_t *mesh) {
        char *name = xstrdup(get_value(mesh->data, "Name"));
 
@@ -559,6 +724,19 @@ static bool finalize_join(meshlink_handle_t *mesh) {
 
        fprintf(f, "Name = %s\n", name);
 
+       // Wipe all old host config files and invitations
+       snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
+       deltree(filename);
+
+       if(mkdir(filename, 0777) && errno != EEXIST) {
+               logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
+               return false;
+       }
+
+       snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
+       deltree(filename);
+
+       // Create a new host config file for ourself
        snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
        FILE *fh = fopen(filename, "w");
 
@@ -690,8 +868,10 @@ static bool finalize_join(meshlink_handle_t *mesh) {
        sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
        free(b64key);
 
+       free(mesh->name);
        free(mesh->self->name);
        free(mesh->self->connection->name);
+       mesh->name = xstrdup(name);
        mesh->self->name = xstrdup(name);
        mesh->self->connection->name = name;
 
@@ -742,7 +922,7 @@ static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint
                return finalize_join(mesh);
 
        case 2:
-               logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
+               logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
                shutdown(mesh->sock, SHUT_RDWR);
                mesh->success = true;
                break;
@@ -830,6 +1010,8 @@ static const char *errstr[] = {
        [MESHLINK_ESTORAGE] = "Storage error",
        [MESHLINK_ENETWORK] = "Network error",
        [MESHLINK_EPEER] = "Error communicating with peer",
+       [MESHLINK_ENOTSUP] = "Operation not supported",
+       [MESHLINK_EBUSY] = "MeshLink instance already in use",
 };
 
 const char *meshlink_strerror(meshlink_errno_t err) {
@@ -927,14 +1109,14 @@ static void add_local_addresses(meshlink_handle_t *mesh) {
 
        // IPv4 example.org
 
-       if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
+       if(getlocaladdrname("93.184.216.34", host, sizeof(host), mesh->netns)) {
                snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
                append_config_file(mesh, mesh->name, "Address", entry);
        }
 
        // IPv6 example.org
 
-       if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
+       if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host), mesh->netns)) {
                snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
                append_config_file(mesh, mesh->name, "Address", entry);
        }
@@ -990,30 +1172,120 @@ static bool meshlink_setup(meshlink_handle_t *mesh) {
        return true;
 }
 
+static void *setup_network_in_netns_thread(void *arg) {
+       meshlink_handle_t *mesh = arg;
+
+       if(setns(mesh->netns, CLONE_NEWNET) != 0) {
+               return NULL;
+       }
+
+       bool success = setup_network(mesh);
+       add_local_addresses(mesh);
+       return success ? arg : NULL;
+}
+
+meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
+       if(!confbase || !*confbase) {
+               logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
+               meshlink_errno = MESHLINK_EINVAL;
+               return NULL;
+       }
+
+       if(!appname || !*appname) {
+               logger(NULL, MESHLINK_ERROR, "No appname given!\n");
+               meshlink_errno = MESHLINK_EINVAL;
+               return NULL;
+       }
+
+       if(strchr(appname, ' ')) {
+               logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
+               meshlink_errno = MESHLINK_EINVAL;
+               return NULL;
+       }
+
+       if(!name || !*name) {
+               logger(NULL, MESHLINK_ERROR, "No name given!\n");
+               //return NULL;
+       } else { //check name only if there is a name != NULL
+               if(!check_id(name)) {
+                       logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
+                       meshlink_errno = MESHLINK_EINVAL;
+                       return NULL;
+               }
+       }
+
+       if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
+               logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
+               meshlink_errno = MESHLINK_EINVAL;
+               return NULL;
+       }
+
+       meshlink_open_params_t *params = xzalloc(sizeof * params);
+
+       params->confbase = xstrdup(confbase);
+       params->name = xstrdup(name);
+       params->appname = xstrdup(appname);
+       params->devclass = devclass;
+       params->netns = -1;
+
+       return params;
+}
+
+void meshlink_open_params_free(meshlink_open_params_t *params) {
+       if(!params) {
+               meshlink_errno = MESHLINK_EINVAL;
+               return;
+       }
+
+       free(params->confbase);
+       free(params->name);
+       free(params->appname);
+
+       free(params);
+}
+
 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
+       /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
+       meshlink_open_params_t params = {NULL};
+
+       params.confbase = (char *)confbase;
+       params.name = (char *)name;
+       params.appname = (char *)appname;
+       params.devclass = devclass;
+       params.netns = -1;
+
+       return meshlink_open_ex(&params);
+}
+meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
        // Validate arguments provided by the application
        bool usingname = false;
 
        logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
 
-       if(!confbase || !*confbase) {
+       if(!params->confbase || !*params->confbase) {
                logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
                meshlink_errno = MESHLINK_EINVAL;
                return NULL;
        }
 
-       if(!appname || !*appname) {
+       if(!params->appname || !*params->appname) {
                logger(NULL, MESHLINK_ERROR, "No appname given!\n");
                meshlink_errno = MESHLINK_EINVAL;
                return NULL;
        }
 
-       if(!name || !*name) {
+       if(strchr(params->appname, ' ')) {
+               logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
+               meshlink_errno = MESHLINK_EINVAL;
+               return NULL;
+       }
+
+       if(!params->name || !*params->name) {
                logger(NULL, MESHLINK_ERROR, "No name given!\n");
                //return NULL;
        } else { //check name only if there is a name != NULL
 
-               if(!check_id(name)) {
+               if(!check_id(params->name)) {
                        logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
                        meshlink_errno = MESHLINK_EINVAL;
                        return NULL;
@@ -1022,20 +1294,23 @@ meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const c
                }
        }
 
-       if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
+       if((int)params->devclass < 0 || params->devclass > _DEV_CLASS_MAX) {
                logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
                meshlink_errno = MESHLINK_EINVAL;
                return NULL;
        }
 
        meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
-       mesh->confbase = xstrdup(confbase);
-       mesh->appname = xstrdup(appname);
-       mesh->devclass = devclass;
+       mesh->confbase = xstrdup(params->confbase);
+       mesh->appname = xstrdup(params->appname);
+       mesh->devclass = params->devclass;
        mesh->discovery = true;
+       mesh->invitation_timeout = 604800; // 1 week
+       mesh->netns = params->netns;
+       mesh->submeshes = NULL;
 
        if(usingname) {
-               mesh->name = xstrdup(name);
+               mesh->name = xstrdup(params->name);
        }
 
        // initialize mutex
@@ -1053,7 +1328,7 @@ meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const c
        // Check whether meshlink.conf already exists
 
        char filename[PATH_MAX];
-       snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
+       snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", params->confbase);
 
        if(access(filename, R_OK)) {
                if(errno == ENOENT) {
@@ -1070,6 +1345,34 @@ meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const c
                }
        }
 
+       // Open the configuration file and lock it
+
+       mesh->conffile = fopen(filename, "r");
+
+       if(!mesh->conffile) {
+               logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
+               meshlink_close(mesh);
+               meshlink_errno = MESHLINK_ESTORAGE;
+               return NULL;
+       }
+
+#ifdef FD_CLOEXEC
+       fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
+#endif
+
+#ifdef HAVE_MINGW
+       // TODO: use _locking()?
+#else
+
+       if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
+               logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
+               meshlink_close(mesh);
+               meshlink_errno = MESHLINK_EBUSY;
+               return NULL;
+       }
+
+#endif
+
        // Read the configuration
 
        init_configuration(&mesh->config);
@@ -1090,23 +1393,66 @@ meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const c
        // Setup up everything
        // TODO: we should not open listening sockets yet
 
-       if(!setup_network(mesh)) {
+       bool success = false;
+
+       if(mesh->netns != -1) {
+               pthread_t thr;
+
+               if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
+                       void *retval = NULL;
+                       success = pthread_join(thr, &retval) == 0 && retval;
+               }
+       } else {
+               success = setup_network(mesh);
+               add_local_addresses(mesh);
+       }
+
+       if(!success) {
                meshlink_close(mesh);
                meshlink_errno = MESHLINK_ENETWORK;
                return NULL;
        }
 
-       add_local_addresses(mesh);
-
        idle_set(&mesh->loop, idle, mesh);
 
        logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
        return mesh;
 }
 
+meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t  *mesh, const char *submesh) {
+       meshlink_submesh_t *s = NULL;
+
+       if(!mesh) {
+               logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
+               meshlink_errno = MESHLINK_EINVAL;
+               return NULL;
+       }
+
+       if(!submesh || !*submesh) {
+               logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
+               meshlink_errno = MESHLINK_EINVAL;
+               return NULL;
+       }
+
+       //lock mesh->nodes
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+
+       s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
+
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
+
+       return s;
+}
+
 static void *meshlink_main_loop(void *arg) {
        meshlink_handle_t *mesh = arg;
 
+       if(mesh->netns != -1) {
+               if(setns(mesh->netns, CLONE_NEWNET) != 0) {
+                       return NULL;
+               }
+       }
+
        pthread_mutex_lock(&(mesh->mesh_mutex));
 
        try_outgoing_connections(mesh);
@@ -1168,10 +1514,14 @@ bool meshlink_start(meshlink_handle_t *mesh) {
 
        mesh->threadstarted = true;
 
+#if HAVE_CATTA
+
        if(mesh->discovery) {
                discovery_start(mesh);
        }
 
+#endif
+
        pthread_mutex_unlock(&(mesh->mesh_mutex));
        return true;
 }
@@ -1185,11 +1535,15 @@ void meshlink_stop(meshlink_handle_t *mesh) {
        pthread_mutex_lock(&(mesh->mesh_mutex));
        logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
 
+#if HAVE_CATTA
+
        // Stop discovery
        if(mesh->discovery) {
                discovery_stop(mesh);
        }
 
+#endif
+
        // Shut down the main thread
        event_loop_stop(&mesh->loop);
 
@@ -1266,42 +1620,24 @@ void meshlink_close(meshlink_handle_t *mesh) {
 
        ecdsa_free(mesh->invitation_key);
 
+       if(mesh->netns != -1) {
+               close(mesh->netns);
+       }
+
        free(mesh->name);
        free(mesh->appname);
        free(mesh->confbase);
        pthread_mutex_destroy(&(mesh->mesh_mutex));
 
+       if(mesh->conffile) {
+               fclose(mesh->conffile);
+       }
+
        memset(mesh, 0, sizeof(*mesh));
 
        free(mesh);
 }
 
-static void deltree(const char *dirname) {
-       DIR *d = opendir(dirname);
-
-       if(d) {
-               struct dirent *ent;
-
-               while((ent = readdir(d))) {
-                       if(ent->d_name[0] == '.') {
-                               continue;
-                       }
-
-                       char filename[PATH_MAX];
-                       snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
-
-                       if(unlink(filename)) {
-                               deltree(filename);
-                       }
-               }
-
-               closedir(d);
-       }
-
-       rmdir(dirname);
-       return;
-}
-
 bool meshlink_destroy(const char *confbase) {
        if(!confbase) {
                meshlink_errno = MESHLINK_EINVAL;
@@ -1349,6 +1685,17 @@ void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_c
        pthread_mutex_unlock(&(mesh->mesh_mutex));
 }
 
+void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
+       if(!mesh) {
+               meshlink_errno = MESHLINK_EINVAL;
+               return;
+       }
+
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+       mesh->node_duplicate_cb = cb;
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
+}
+
 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
        if(mesh) {
                pthread_mutex_lock(&(mesh->mesh_mutex));
@@ -1379,6 +1726,13 @@ bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const
                return false;
        }
 
+       node_t *n = (node_t *)destination;
+
+       if(n->status.blacklisted) {
+               logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
+               return false;
+       }
+
        // Prepare the packet
        vpn_packet_t *packet = malloc(sizeof(*packet));
 
@@ -1529,6 +1883,114 @@ meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_
        return result;
 }
 
+static meshlink_node_t **meshlink_get_all_nodes_by_condition(meshlink_handle_t *mesh, const void *condition, meshlink_node_t **nodes, size_t *nmemb, search_node_by_condition_t search_node) {
+       meshlink_node_t **result;
+
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+
+       *nmemb = 0;
+
+       for splay_each(node_t, n, mesh->nodes) {
+               if(true == search_node(n, condition)) {
+                       *nmemb = *nmemb + 1;
+               }
+       }
+
+       if(*nmemb == 0) {
+               free(nodes);
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
+               return NULL;
+       }
+
+       result = realloc(nodes, *nmemb * sizeof(*nodes));
+
+       if(result) {
+               meshlink_node_t **p = result;
+
+               for splay_each(node_t, n, mesh->nodes) {
+                       if(true == search_node(n, condition)) {
+                               *p++ = (meshlink_node_t *)n;
+                       }
+               }
+       } else {
+               *nmemb = 0;
+               free(nodes);
+               meshlink_errno = MESHLINK_ENOMEM;
+       }
+
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
+
+       return result;
+}
+
+static bool search_node_by_dev_class(const node_t *node, const void *condition) {
+       dev_class_t *devclass = (dev_class_t *)condition;
+
+       if(*devclass == node->devclass) {
+               return true;
+       }
+
+       return false;
+}
+
+static bool search_node_by_submesh(const node_t *node, const void *condition) {
+       if(condition == node->submesh) {
+               return true;
+       }
+
+       return false;
+}
+
+meshlink_node_t **meshlink_get_all_nodes_by_dev_class(meshlink_handle_t *mesh, dev_class_t devclass, meshlink_node_t **nodes, size_t *nmemb) {
+       if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
+               meshlink_errno = MESHLINK_EINVAL;
+               return NULL;
+       }
+
+       return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
+}
+
+meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
+       if(!mesh || !submesh || !nmemb) {
+               meshlink_errno = MESHLINK_EINVAL;
+               return NULL;
+       }
+
+       return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
+}
+
+dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
+       if(!mesh || !node) {
+               meshlink_errno = MESHLINK_EINVAL;
+               return -1;
+       }
+
+       dev_class_t devclass;
+
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+
+       devclass = ((node_t *)node)->devclass;
+
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
+
+       return devclass;
+}
+
+meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
+       if(!mesh || !node) {
+               meshlink_errno = MESHLINK_EINVAL;
+               return NULL;
+       }
+
+       node_t *n = (node_t *)node;
+
+       meshlink_submesh_t *s;
+
+       s = (meshlink_submesh_t *)n->submesh;
+
+       return s;
+}
+
 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
        if(!mesh || !data || !len || !signature || !siglen) {
                meshlink_errno = MESHLINK_EINVAL;
@@ -1744,7 +2206,7 @@ bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *no
 }
 
 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
-       return meshlink_set_canonical_address(mesh, mesh->self, address, NULL);
+       return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
 }
 
 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
@@ -1832,12 +2294,30 @@ done:
        return rval;
 }
 
-char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
+void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
+       mesh->invitation_timeout = timeout;
+}
+
+char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
+       meshlink_submesh_t *s = NULL;
+
        if(!mesh) {
                meshlink_errno = MESHLINK_EINVAL;
                return NULL;
        }
 
+       if(submesh) {
+               s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
+
+               if(s != submesh) {
+                       logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
+                       meshlink_errno = MESHLINK_EINVAL;
+                       return NULL;
+               }
+       } else {
+               s = (meshlink_submesh_t *)mesh->self->submesh;
+       }
+
        pthread_mutex_lock(&(mesh->mesh_mutex));
 
        // Check validity of the new node's name
@@ -1868,7 +2348,7 @@ char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
        }
 
        // Get the local address
-       char *address = get_my_hostname(mesh);
+       char *address = get_my_hostname(mesh, flags);
 
        if(!address) {
                logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
@@ -1925,6 +2405,11 @@ char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
 
        // Fill in the details.
        fprintf(f, "Name = %s\n", name);
+
+       if(s) {
+               fprintf(f, "SubMesh = %s\n", s->name);
+       }
+
        fprintf(f, "ConnectTo = %s\n", mesh->self->name);
 
        // Copy Broadcast and Mode
@@ -1970,6 +2455,10 @@ char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
        return url;
 }
 
+char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
+       return meshlink_invite_ex(mesh, submesh, name, 0);
+}
+
 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
        if(!mesh || !invitation) {
                meshlink_errno = MESHLINK_EINVAL;
@@ -1990,7 +2479,7 @@ bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
        char copy[strlen(invitation) + 1];
        strcpy(copy, invitation);
 
-       // Split the invitation URL into hostname, port, key hash and cookie.
+       // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
 
        char *slash = strchr(copy, '/');
 
@@ -2005,13 +2494,7 @@ bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
        }
 
        char *address = copy;
-       char *port = strrchr(address, ':');
-
-       if(!port) {
-               goto invalid;
-       }
-
-       *port++ = 0;
+       char *port = NULL;
 
        if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
                goto invalid;
@@ -2038,6 +2521,15 @@ bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
                        *comma++ = 0;
                }
 
+               // Split of the port
+               port = strrchr(address, ':');
+
+               if(!port) {
+                       goto invalid;
+               }
+
+               *port++ = 0;
+
                // IPv6 address are enclosed in brackets, per RFC 3986
                if(*address == '[') {
                        address++;
@@ -2049,7 +2541,7 @@ bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
 
                        *bracket++ = 0;
 
-                       if(comma && bracket != comma) {
+                       if(*bracket) {
                                goto invalid;
                        }
                }
@@ -2059,7 +2551,7 @@ bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
 
                if(ai) {
                        for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
-                               mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
+                               mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
 
                                if(mesh->sock == -1) {
                                        logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
@@ -2101,7 +2593,7 @@ bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
 
        mesh->blen = 0;
 
-       if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
+       if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
                logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
                closesocket(mesh->sock);
                meshlink_errno = MESHLINK_ENETWORK;
@@ -2330,14 +2822,46 @@ void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
 
        node_t *n;
        n = (node_t *)node;
+
+       if(n == mesh->self) {
+               logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
+               meshlink_errno = MESHLINK_EINVAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
+               return;
+       }
+
+       if(n->status.blacklisted) {
+               logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
+               return;
+       }
+
        n->status.blacklisted = true;
        logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
 
        //Make blacklisting persistent in the config file
        append_config_file(mesh, n->name, "blacklisted", "yes");
 
+       //Immediately terminate any connections we have with the blacklisted node
+       for list_each(connection_t, c, mesh->connections) {
+               if(c->node == n) {
+                       terminate_connection(mesh, c, c->status.active);
+               }
+       }
+
+       utcp_abort_all_connections(n->utcp);
+
+       n->mtu = 0;
+       n->minmtu = 0;
+       n->maxmtu = MTU;
+       n->mtuprobes = 0;
+       n->status.udp_confirmed = false;
+
+       if(n->status.reachable) {
+               update_node_status(mesh, n);
+       }
+
        pthread_mutex_unlock(&(mesh->mesh_mutex));
-       return;
 }
 
 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
@@ -2349,9 +2873,22 @@ void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
        pthread_mutex_lock(&(mesh->mesh_mutex));
 
        node_t *n = (node_t *)node;
+
+       if(!n->status.blacklisted) {
+               logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
+               meshlink_errno = MESHLINK_EINVAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
+               return;
+       }
+
        n->status.blacklisted = false;
 
-       //TODO: remove blacklisted = yes from the config file
+       if(n->status.reachable) {
+               update_node_status(mesh, n);
+       }
+
+       //Remove blacklisting from the config file
+       append_config_file(mesh, n->name, "blacklisted", NULL);
 
        pthread_mutex_unlock(&(mesh->mesh_mutex));
        return;
@@ -2540,6 +3077,11 @@ meshlink_channel_t *meshlink_channel_open_ex(meshlink_handle_t *mesh, meshlink_n
                }
        }
 
+       if(n->status.blacklisted) {
+               logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
+               return NULL;
+       }
+
        meshlink_channel_t *channel = xzalloc(sizeof(*channel));
        channel->node = n;
        channel->receive_cb = cb;
@@ -2594,7 +3136,7 @@ ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *chann
 
        // TODO: more finegrained locking.
        // Ideally we want to put the data into the UTCP connection's send buffer.
-       // Then, preferrably only if there is room in the receiver window,
+       // Then, preferably only if there is room in the receiver window,
        // kick the meshlink thread to go send packets.
 
        pthread_mutex_lock(&mesh->mesh_mutex);
@@ -2617,17 +3159,46 @@ uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t
        return channel->c->flags;
 }
 
+size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
+       if(!mesh || !channel) {
+               meshlink_errno = MESHLINK_EINVAL;
+               return -1;
+       }
+
+       return utcp_get_sendq(channel->c);
+}
+
+size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
+       if(!mesh || !channel) {
+               meshlink_errno = MESHLINK_EINVAL;
+               return -1;
+       }
+
+       return utcp_get_recvq(channel->c);
+}
+
 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
        if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
                n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
        }
 
        if(mesh->node_status_cb) {
-               mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
+               mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
+       }
+}
+
+void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
+       if(!mesh->node_duplicate_cb || n->status.duplicate) {
+               return;
        }
+
+       n->status.duplicate = true;
+       mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
 }
 
 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
+#if HAVE_CATTA
+
        if(!mesh) {
                meshlink_errno = MESHLINK_EINVAL;
                return;
@@ -2651,6 +3222,11 @@ void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
 
 end:
        pthread_mutex_unlock(&mesh->mesh_mutex);
+#else
+       (void)mesh;
+       (void)enable;
+       meshlink_errno = MESHLINK_ENOTSUP;
+#endif
 }
 
 static void __attribute__((constructor)) meshlink_init(void) {