]> git.meshlink.io Git - meshlink/commitdiff
Merge branch 'mesh_topology_output' into roles
authorNiklas Hofmann <niklas.hofmann@everbase.net>
Wed, 13 Aug 2014 11:30:16 +0000 (13:30 +0200)
committerNiklas Hofmann <niklas.hofmann@everbase.net>
Wed, 13 Aug 2014 11:30:16 +0000 (13:30 +0200)
1  2 
src/meshlink.c
src/meshlink.h
src/meshlink_internal.h
src/net.c

diff --combined src/meshlink.c
index bf1eb92bcdf0719ac99eb1780b4e5bbc4d173854,e84aafcac9e3a7d3197e278eb186c510b0c5a232..1d52724e26d6e31b52255bbb2ae8976e4edbb770
@@@ -742,14 -742,16 +742,16 @@@ static bool meshlink_setup(meshlink_han
        return true;
  }
  
 -meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dclass_t dclass) {
 -      return meshlink_open_with_size(confbase, name, appname, dclass, sizeof(meshlink_handle_t));
 +meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
 +      return meshlink_open_with_size(confbase, name, appname, devclass, sizeof(meshlink_handle_t));
  }
  
 -meshlink_handle_t *meshlink_open_with_size(const char *confbase, const char *name, const char* appname, dclass_t dclass, size_t size) {
 +meshlink_handle_t *meshlink_open_with_size(const char *confbase, const char *name, const char* appname, dev_class_t devclass, size_t size) {
  
        // Validate arguments provided by the application
        bool usingname = false;
+       
+       logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
  
        if(!confbase || !*confbase) {
                logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
                } else { usingname = true;}
        }
  
 +      if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
 +              logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
 +              meshlink_errno = MESHLINK_EINVAL;
 +              return NULL;
 +      }
 +
        meshlink_handle_t *mesh = xzalloc(size);
        mesh->confbase = xstrdup(confbase);
        mesh->appname = xstrdup(appname);
 -      mesh->dclass = dclass;
 +      mesh->devclass = devclass;
        if (usingname) mesh->name = xstrdup(name);
-       pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
+       // initialize mutex
+       pthread_mutexattr_t attr;
+       pthread_mutexattr_init(&attr);
+       pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
+       pthread_mutex_init(&(mesh->mesh_mutex), &attr);
+       
        mesh->threadstarted = false;
        event_loop_init(&mesh->loop);
        mesh->loop.data = mesh;
                return NULL;
        }
  
+       logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
        return mesh;
  }
  
  static void *meshlink_main_loop(void *arg) {
        meshlink_handle_t *mesh = arg;
  
+       pthread_mutex_lock(&(mesh->mesh_mutex));
        try_outgoing_connections(mesh);
  
        logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
        main_loop(mesh);
        logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
  
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return NULL;
  }
  
  bool meshlink_start(meshlink_handle_t *mesh) {
-       logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
        if(!mesh) {
                meshlink_errno = MESHLINK_EINVAL;
                return false;
        }
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+       
+       logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
  
        // TODO: open listening sockets first
  
        if(!mesh->name ) {
                logger(mesh, MESHLINK_DEBUG, "No name given!\n");
                meshlink_errno = MESHLINK_EINVAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
                logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
                memset(&mesh->thread, 0, sizeof mesh->thread);
                meshlink_errno = MESHLINK_EINTERNAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
  
        discovery_start(mesh);
  
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return true;
  }
  
  void meshlink_stop(meshlink_handle_t *mesh) {
-       logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
-       
        if(!mesh) {
                meshlink_errno = MESHLINK_EINVAL;
                return;
        }
  
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+       logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
        // Stop discovery
        discovery_stop(mesh);
  
        shutdown(s->tcp.fd, SHUT_RDWR);
  
        // Wait for the main thread to finish
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        pthread_join(mesh->thread, NULL);
+       pthread_mutex_lock(&(mesh->mesh_mutex));
        mesh->threadstarted = false;
  
        // Fix the socket
                logger(mesh, MESHLINK_ERROR, "Could not repair listenen socket!");
        else
                io_add(&mesh->loop, &s->tcp, handle_new_meta_connection, s, s->tcp.fd, IO_READ);
+       
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
  }
  
  void meshlink_close(meshlink_handle_t *mesh) {
                return;
        }
  
+       // lock is not released after this
+       pthread_mutex_lock(&(mesh->mesh_mutex));
        // Close and free all resources used.
  
        close_network_connections(mesh);
        free(mesh->name);
        free(mesh->appname);
        free(mesh->confbase);
+       pthread_mutex_destroy(&(mesh->mesh_mutex));
  
        memset(mesh, 0, sizeof *mesh);
  
@@@ -955,7 -972,9 +978,9 @@@ void meshlink_set_receive_cb(meshlink_h
                return;
        }
  
+       pthread_mutex_lock(&(mesh->mesh_mutex));
        mesh->receive_cb = cb;
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
  }
  
  void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
                return;
        }
  
+       pthread_mutex_lock(&(mesh->mesh_mutex));
        mesh->node_status_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));
                mesh->log_cb = cb;
                mesh->log_level = cb ? level : 0;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
        } else {
                global_log_cb = cb;
                global_log_level = cb ? level : 0;
@@@ -991,6 -1014,8 +1020,8 @@@ bool meshlink_send(meshlink_handle_t *m
                return false;
        }
  
+       pthread_mutex_lock(&(mesh->mesh_mutex));
        //add packet to the queue
        outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
        packet_in_queue->destination=destination;
        packet_in_queue->len=len;
        if(!meshlink_queue_push(&mesh->outpacketqueue, packet_in_queue)) {
                free(packet_in_queue);
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        //notify event loop
        signal_trigger(&(mesh->loop),&(mesh->datafromapp));
+       
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return true;
  }
  
  void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+       
        vpn_packet_t packet;
        meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
  
        outpacketqueue_t* p = meshlink_queue_pop(&mesh->outpacketqueue);
        if(!p)
+       {
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return;
+       }
  
        if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                //log something
-               return ;
+               return;
        }
  
        packet.probe = false;
          mesh->self->in_packets++;
          mesh->self->in_bytes += packet.len;
          route(mesh, mesh->self, &packet);
+       
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return ;
  }
  
@@@ -1038,14 -1074,22 +1080,22 @@@ ssize_t meshlink_get_pmtu(meshlink_hand
                meshlink_errno = MESHLINK_EINVAL;
                return -1;
        }
+       pthread_mutex_lock(&(mesh->mesh_mutex));
  
        node_t *n = (node_t *)destination;
-       if(!n->status.reachable)
+       if(!n->status.reachable) {
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return 0;
-       else if(n->mtuprobes > 30 && n->minmtu)
+       
+       }
+       else if(n->mtuprobes > 30 && n->minmtu) {
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return n->minmtu;
-       else
+       }
+       else {
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return MTU;
+       }
  }
  
  char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
                meshlink_errno = MESHLINK_EINVAL;
                return NULL;
        }
+       pthread_mutex_lock(&(mesh->mesh_mutex));
  
        node_t *n = (node_t *)node;
  
        if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
                meshlink_errno = MESHLINK_EINTERNAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        if(!fingerprint)
                meshlink_errno = MESHLINK_EINTERNAL;
  
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return fingerprint;
  }
  
@@@ -1075,7 -1122,12 +1128,12 @@@ meshlink_node_t *meshlink_get_node(mesh
                return NULL;
        }
  
-       return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
+       meshlink_node_t *node = NULL;
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+       node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
+       return node;
  }
  
  meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
        meshlink_node_t **result;
  
        //lock mesh->nodes
-       pthread_mutex_lock(&(mesh->nodes_mutex));
+       pthread_mutex_lock(&(mesh->mesh_mutex));
  
        *nmemb = mesh->nodes->count;
        result = realloc(nodes, *nmemb * sizeof *nodes);
                meshlink_errno = MESHLINK_ENOMEM;
        }
  
-       pthread_mutex_unlock(&(mesh->nodes_mutex));
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
  
        return result;
  }
@@@ -1118,12 -1170,16 +1176,16 @@@ bool meshlink_sign(meshlink_handle_t *m
                return false;
        }
  
+       pthread_mutex_lock(&(mesh->mesh_mutex));
        if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
                meshlink_errno = MESHLINK_EINTERNAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        *siglen = MESHLINK_SIGLEN;
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return true;
  }
  
@@@ -1138,23 -1194,32 +1200,32 @@@ bool meshlink_verify(meshlink_handle_t 
                return false;
        }
  
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+       bool rval = false;
        struct node_t *n = (struct node_t *)source;
        node_read_ecdsa_public_key(mesh, n);
        if(!n->ecdsa) {
                meshlink_errno = MESHLINK_EINTERNAL;
-               return false;
+               rval = false;
+       } else {
+               rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
        }
-       return ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
+       return rval;
  }
  
  static bool refresh_invitation_key(meshlink_handle_t *mesh) {
        char filename[PATH_MAX];
+       
+       pthread_mutex_lock(&(mesh->mesh_mutex));
  
        snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
        if(mkdir(filename, 0700) && errno != EEXIST) {
                logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
                meshlink_errno = MESHLINK_ESTORAGE;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        if(!dir) {
                logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
                meshlink_errno = MESHLINK_ESTORAGE;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
                logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
                closedir(dir);
                meshlink_errno = MESHLINK_ESTORAGE;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
                }
        }
  
-       if(mesh->invitation_key)
+       if(mesh->invitation_key) {
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return true;
+       }
  
        // Create a new key if necessary.
        FILE *f = fopen(filename, "r");
                if(errno != ENOENT) {
                        logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
                        meshlink_errno = MESHLINK_ESTORAGE;
+                       pthread_mutex_unlock(&(mesh->mesh_mutex));
                        return false;
                }
  
                if(!mesh->invitation_key) {
                        logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
                        meshlink_errno = MESHLINK_EINTERNAL;
+                       pthread_mutex_unlock(&(mesh->mesh_mutex));
                        return false;
                }
                f = fopen(filename, "w");
                if(!f) {
                        logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
                        meshlink_errno = MESHLINK_ESTORAGE;
+                       pthread_mutex_unlock(&(mesh->mesh_mutex));
                        return false;
                }
                chmod(filename, 0600);
                }
        }
  
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return mesh->invitation_key;
  }
  
@@@ -1252,16 -1325,23 +1331,23 @@@ bool meshlink_add_address(meshlink_hand
                meshlink_errno = MESHLINK_EINVAL;
                return false;
        }
+       
+       bool rval = false;
+       pthread_mutex_lock(&(mesh->mesh_mutex));
  
        for(const char *p = address; *p; p++) {
                if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
                        continue;
                logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
                meshlink_errno = MESHLINK_EINVAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
-       return append_config_file(mesh, mesh->self->name, "Address", address);
+       rval = append_config_file(mesh, mesh->self->name, "Address", address);
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
+       return rval;
  }
  
  char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
                meshlink_errno = MESHLINK_EINVAL;
                return NULL;
        }
+       
+       pthread_mutex_lock(&(mesh->mesh_mutex));
  
        // Check validity of the new node's name
        if(!check_id(name)) {
                logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
                meshlink_errno = MESHLINK_EINVAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return NULL;
        }
  
        if(!access(filename, F_OK)) {
                logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
                meshlink_errno = MESHLINK_EEXIST;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return NULL;
        }
  
        if(meshlink_get_node(mesh, name)) {
                logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
                meshlink_errno = MESHLINK_EEXIST;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return NULL;
        }
  
        if(!address) {
                logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
                meshlink_errno = MESHLINK_ERESOLV;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return NULL;
        }
  
        if(!refresh_invitation_key(mesh)) {
                meshlink_errno = MESHLINK_EINTERNAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return NULL;
        }
  
        if(!ifd) {
                logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
                meshlink_errno = MESHLINK_ESTORAGE;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return NULL;
        }
        FILE *f = fdopen(ifd, "w");
        } else {
                logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
                meshlink_errno = MESHLINK_ESTORAGE;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return NULL;
        }
  
        xasprintf(&url, "%s/%s%s", address, hash, cookie);
        free(address);
  
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return url;
  }
  
@@@ -1388,6 -1478,8 +1484,8 @@@ bool meshlink_join(meshlink_handle_t *m
                meshlink_errno = MESHLINK_EINVAL;
                return false;
        }
+       
+       pthread_mutex_lock(&(mesh->mesh_mutex));
  
        //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
        char copy[strlen(invitation) + 1];
        ecdsa_t *key = ecdsa_generate();
        if(!key) {
                meshlink_errno = MESHLINK_EINTERNAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
        if(!ai) {
                meshlink_errno = MESHLINK_ERESOLV;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
                logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
                freeaddrinfo(ai);
                meshlink_errno = MESHLINK_ENETWORK;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
                closesocket(mesh->sock);
                freeaddrinfo(ai);
                meshlink_errno = MESHLINK_ENETWORK;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
                logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
                closesocket(mesh->sock);
                meshlink_errno = MESHLINK_ENETWORK;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
                logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
                closesocket(mesh->sock);
                meshlink_errno = MESHLINK_ENETWORK;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        if(sha512(fingerprint, strlen(fingerprint), hishash)) {
                logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
                meshlink_errno = MESHLINK_EINTERNAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
        if(memcmp(hishash, mesh->hash, 18)) {
                logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
                meshlink_errno = MESHLINK_EPEER;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
  
        }
        ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
        if(!hiskey) {
                meshlink_errno = MESHLINK_EINTERNAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        // Start an SPTPS session
        if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
                meshlink_errno = MESHLINK_EINTERNAL;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        // Feed rest of input buffer to SPTPS
        if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
                meshlink_errno = MESHLINK_EPEER;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
                                continue;
                        logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
                        meshlink_errno = MESHLINK_ENETWORK;
+                       pthread_mutex_unlock(&(mesh->mesh_mutex));
                        return false;
                }
  
                if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
                        meshlink_errno = MESHLINK_EPEER;
+                       pthread_mutex_unlock(&(mesh->mesh_mutex));
                        return false;
                }
        }
        if(!mesh->success) {
                logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
                meshlink_errno = MESHLINK_EPEER;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return true;
  
  invalid:
        logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
        meshlink_errno = MESHLINK_EINVAL;
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return false;
  }
  
@@@ -1565,12 -1673,15 +1679,15 @@@ char *meshlink_export(meshlink_handle_
                return NULL;
        }
  
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+       
        char filename[PATH_MAX];
        snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
        FILE *f = fopen(filename, "r");
        if(!f) {
                logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
                meshlink_errno = MESHLINK_ESTORAGE;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return NULL;
        }
  
                logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
                fclose(f);
                meshlink_errno = MESHLINK_ESTORAGE;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return NULL;
        }
  
        fclose(f);
        buf[len - 1] = 0;
+       
+       pthread_mutex_lock(&(mesh->mesh_mutex));
        return buf;
  }
  
@@@ -1598,10 -1712,13 +1718,13 @@@ bool meshlink_import(meshlink_handle_t 
                meshlink_errno = MESHLINK_EINVAL;
                return false;
        }
+       
+       pthread_mutex_lock(&(mesh->mesh_mutex));
  
        if(strncmp(data, "Name = ", 7)) {
                logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
                meshlink_errno = MESHLINK_EPEER;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        if(!end) {
                logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
                meshlink_errno = MESHLINK_EPEER;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        if(!check_id(name)) {
                logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
                meshlink_errno = MESHLINK_EPEER;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        if(!access(filename, F_OK)) {
                logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
                meshlink_errno = MESHLINK_EEXIST;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        if(errno != ENOENT) {
                logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
                meshlink_errno = MESHLINK_ESTORAGE;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
        if(!f) {
                logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
                meshlink_errno = MESHLINK_ESTORAGE;
+               pthread_mutex_unlock(&(mesh->mesh_mutex));
                return false;
        }
  
  
        load_all_nodes(mesh);
  
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return true;
  }
  
@@@ -1657,6 -1780,8 +1786,8 @@@ void meshlink_blacklist(meshlink_handle
                return;
        }
  
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+       
        node_t *n;
        n = (node_t*)node;
        n->status.blacklisted=true;
        //Make blacklisting persistent in the config file
        append_config_file(mesh, n->name, "blacklisted", "yes");
  
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return;
  }
  
@@@ -1674,21 -1800,26 +1806,26 @@@ void meshlink_whitelist(meshlink_handle
                return;
        }
  
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+       
        node_t *n = (node_t *)node;
        n->status.blacklisted = false;
  
        //TODO: remove blacklisted = yes from the config file
  
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return;
  }
  
  /* Hint that a hostname may be found at an address
   * See header file for detailed comment.
   */
extern void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
+ void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
        if(!mesh || !node || !addr)
                return;
        
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+       
        char *host = NULL, *port = NULL, *str = NULL;
        sockaddr2str((const sockaddr_t *)addr, &host, &port);
  
        free(host);
        free(port);
  
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
        // @TODO do we want to fire off a connection attempt right away?
  }
  
+ /* Return an array of edges in the current network graph.
+  * Data captures the current state and will not be updated.
+  * Caller must deallocate data when done.
+  */
+ meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb) {
+       if(!mesh || !nmemb || (*nmemb && !edges)) {
+               meshlink_errno = MESHLINK_EINVAL;
+               return NULL;
+       }
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+       
+       meshlink_edge_t **result = NULL;
+       meshlink_edge_t *copy = NULL;
+       int result_size = 0;
+       result_size = mesh->edges->count;
+       // if result is smaller than edges, we have to dealloc all the excess meshlink_edge_t
+       if(result_size > *nmemb) {
+               result = realloc(edges, result_size * sizeof (meshlink_edge_t*));
+       } else {
+               result = edges;
+       }
+       if(result) {
+               meshlink_edge_t **p = result;
+               int n = 0;
+               for splay_each(edge_t, e, mesh->edges) {
+                       // skip edges that do not represent a two-directional connection
+                       if((!e->reverse) || (e->reverse->to != e->from)) {
+                               result_size--;
+                               continue;
+                       }
+                       n++;
+                       // the first *nmemb members of result can be re-used
+                       if(n > *nmemb) {
+                               copy = xzalloc(sizeof *copy);
+                       }
+                       else {
+                               copy = *p;
+                       }
+                       copy->from = (meshlink_node_t*)e->from;
+                       copy->to = (meshlink_node_t*)e->to;
+                       copy->address = e->address.storage;
+                       copy->options = e->options;
+                       copy->weight = e->weight;
+                       *p++ = copy;
+               }
+               // shrink result to the actual amount of memory used
+               for(int i = *nmemb; i > result_size; i--) {
+                       free(result[i - 1]);
+               }
+               result = realloc(result, result_size * sizeof (meshlink_edge_t*));
+               *nmemb = result_size;
+       } else {
+               *nmemb = 0;
+               free(result);
+               meshlink_errno = MESHLINK_ENOMEM;
+       }
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
+       return result;
+ }
  static void __attribute__((constructor)) meshlink_init(void) {
        crypto_init();
  }
@@@ -1712,11 -1910,19 +1916,11 @@@ static void __attribute__((destructor)
        crypto_exit();
  }
  
 -int weight_from_dclass(dclass_t dclass)
 -{
 -      switch(dclass)
 -      {
 -      case BACKBONE:
 -              return 1;
 -
 -      case STATIONARY:
 -              return 3;
 -
 -      case PORTABLE:
 -              return 6;
 -      }
  
 -      return 9;
 -}
 +/// Device class traits
 +dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX +1] = {
 +      { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
 +      { .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
 +      { .min_connects = 3, .max_connects = 3, .edge_weight = 6 },             // DEV_CLASS_PORTABLE
 +      { .min_connects = 1, .max_connects = 1, .edge_weight = 9 },             // DEV_CLASS_UNKNOWN
 +};
diff --combined src/meshlink.h
index e9c531ff27008bed4a6518aa095a6a8984434d9a,6f104abe5fcb5cc29bedb9f7e048dd465e211e37..7cf1f4445a5e780f20472dbfdac61b5432232381
@@@ -48,6 -48,9 +48,9 @@@ typedef struct meshlink_handle meshlink
  /// A handle for a MeshLink node.
  typedef struct meshlink_node meshlink_node_t;
  
+ /// A handle for a MeshLink edge.
+ typedef struct meshlink_edge meshlink_edge_t;
  /// A handle for a MeshLink channel.
  typedef struct meshlink_channel meshlink_channel_t;
  
@@@ -65,14 -68,12 +68,14 @@@ typedef enum 
        MESHLINK_EPEER, ///< A peer caused an error
  } meshlink_errno_t;
  
 -// Device class
 +/// Device class
  typedef enum {
 -      BACKBONE = 1,
 -      STATIONARY = 2,
 -      PORTABLE = 3
 -} dclass_t;
 +      DEV_CLASS_BACKBONE = 0,
 +      DEV_CLASS_STATIONARY = 1,
 +      DEV_CLASS_PORTABLE = 2,
 +      DEV_CLASS_UNKNOWN = 3,
 +      _DEV_CLASS_MAX = 3
 +} dev_class_t;
  
  /// A variable holding the last encountered error from MeshLink.
  /** This is a thread local variable that contains the error code of the most recent error
@@@ -85,14 -86,12 +88,14 @@@ extern __thread meshlink_errno_t meshli
  #ifndef MESHLINK_INTERNAL_H
  
  struct meshlink_handle {
 -      const char *name;
 +      char *name;
 +      char *appname;
 +      dev_class_t devclass;
        void *priv;
  };
  
  struct meshlink_node {
 -      const char *name; ///< Textual name of this node. It is stored in a nul-terminated C string, which is allocated by MeshLink.
 +      char *name;       ///< Textual name of this node. It is stored in a nul-terminated C string, which is allocated by MeshLink.
        void *priv;       ///< Private pointer which may be set freely by the application, and is never used or modified by MeshLink.
  };
  
@@@ -101,6 -100,22 +104,22 @@@ struct meshlink_channel 
  
  #endif // MESHLINK_INTERNAL_H
  
+ /// An edge in the meshlink network.
+ struct meshlink_edge {
+       struct meshlink_node *from;     ///< Pointer to a node. Node memory is
+                                       //   owned by meshlink and should not be
+                                       //   deallocated. Node contents may be
+                                       //   changed by meshlink.
+       struct meshlink_node *to;       ///< Pointer to a node. Node memory is
+                                         //   owned by meshlink and should not be
+                                         //   deallocated. Node contents may be
+                                         //   changed by meshlink.
+       struct sockaddr_storage address;///< The address information associated
+                                       //   with this edge.
+       uint32_t options;               ///< Edge options. @TODO what are edge options?
+       int weight;                     ///< Weight assigned to this edge.
+ };
  /// Get the text for the given MeshLink error code.
  /** This function returns a pointer to the string containing the description of the given error code.
   *
@@@ -134,15 -149,15 +153,15 @@@ extern const char *meshlink_strerror(me
   *                  After the function returns, the application is free to overwrite or free @a name @a.
   *  @param appname  The application name which will be used in the mesh.
   *                  After the function returns, the application is free to overwrite or free @a name @a.
 - *  @param dclass   The device class which will be used in the mesh.
 + *  @param devclass The device class which will be used in the mesh.
   *
   *  @return         A pointer to a meshlink_handle_t which represents this instance of MeshLink, or NULL in case of an error.
   *                  The pointer is valid until meshlink_close() is called.
   */
 -extern meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dclass_t dclass);
 +extern meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dev_class_t devclass);
  
  /// is used by the C++ wrapper to allocate more memory behind the handle
 -extern meshlink_handle_t *meshlink_open_with_size(const char *confbase, const char *name, const char* appname, dclass_t dclass, size_t size);
 +extern meshlink_handle_t *meshlink_open_with_size(const char *confbase, const char *name, const char* appname, dev_class_t devclass, size_t size);
  
  /// Start MeshLink.
  /** This function causes MeshLink to open network sockets, make outgoing connections, and
@@@ -612,6 -627,40 +631,40 @@@ extern ssize_t meshlink_channel_send(me
   */
  extern void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr);
  
+ /// Get a list of edges.
+ /** This function returns an array with copies of all known bidirectional edges.
+  *  The edges are copied to capture the mesh state at call time, since edges
+  *  mutate frequently. The nodes pointed to within the meshlink_edge_t type
+  *  are not copies; these are the same pointers that one would get from a call
+  *  to meshlink_get_all_nodes().
+  *
+  *  @param mesh         A handle which represents an instance of MeshLink.
+  *  @param edges        A pointer to a previously allocated array of pointers to
+  *                    meshlink_edge_t, or NULL in which case MeshLink will
+  *                    allocate a new array. The application CANNOT supply an
+  *                    array it allocated itself with malloc, but CAN use
+  *                    the return value from the previous call to this function
+  *                    (which is the preferred way).
+  *                      The pointers in the array are valid until meshlink_close() is called.
+  *  @param nmemb        A pointer to a variable holding the number of nodes that
+  *                    are stored in the array. In case the @a nodes @a
+  *                    argument is not NULL, MeshLink might call realloc()
+  *                    on the array to change its size.
+  *                      The contents of this variable will be changed to reflect
+  *                      the new size of the array.
+  *  
+  *  @return             A pointer to an array containing pointers to all known 
+  *                    edges, or NULL in case of an error.
+  *                    If the @a edges @a argument was not NULL, then the
+  *                    retun value can be either the same value or a different
+  *                    value. If the new values is NULL, then the old array
+  *                    will have been freed by Meshlink.
+  *                    The caller must call free() on each element of this
+  *                    array (but not the contents of said elements),
+  *                    as well as the array itself when it is finished.
+  */
+ extern meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb);
  #ifdef __cplusplus
  }
  #endif
diff --combined src/meshlink_internal.h
index 2a8b7ebf601b87aab7d5d25df4dc448a6f4020c0,42e1da537b600f5b0b8b0274b82c3e4a646a2aec..994f25bf9bd5f077403ffc67ec5f484ce6165d50
@@@ -64,7 -64,7 +64,7 @@@ typedef struct outpacketqueue 
  struct meshlink_handle {
        char *name;
        char *appname;
 -      dclass_t dclass;
 +      dev_class_t devclass;
        void *priv;
  
        char *confbase;
@@@ -77,7 -77,7 +77,7 @@@
        pthread_t thread;
        bool threadstarted;
        pthread_mutex_t outpacketqueue_mutex;
-       pthread_mutex_t nodes_mutex;
+       pthread_mutex_t mesh_mutex;
        event_loop_t loop;
        listen_socket_t listen_socket[MAXSOCKETS];
        int listen_sockets;
@@@ -158,13 -158,6 +158,13 @@@ extern void meshlink_send_from_queue(ev
  extern meshlink_log_level_t global_log_level;
  extern meshlink_log_cb_t global_log_cb;
  
 -extern int weight_from_dclass(dclass_t dclass);
 +/// Device class traits
 +typedef struct {
 +      unsigned int min_connects;
 +      unsigned int max_connects;
 +      int edge_weight;
 +} dev_class_traits_t;
 +
 +extern dev_class_traits_t dev_class_traits[];
  
  #endif // MESHLINK_INTERNAL_H
diff --combined src/net.c
index c33c69c3062beeddbbc882464302111683ad4d59,c615b893031a63cf727dfe89ccd2d17b1edaaeef..80e866a0ad461fc49bce1794379044ca97e2e33c
+++ b/src/net.c
@@@ -31,8 -31,6 +31,8 @@@
  #include "protocol.h"
  #include "xalloc.h"
  
 +#include <assert.h>
 +
  static const int min(int a, int b) {
        return a < b ? a : b;
  }
@@@ -131,157 -129,75 +131,157 @@@ static void timeout_handler(event_loop_
        timeout_set(&mesh->loop, data, &(struct timeval){mesh->pingtimeout, rand() % 100000});
  }
  
 -/// Utility function to establish connections based on condition check
 -/** The function iterates over all nodes, but skips those that do
 - *  not pass the condition check.
 - *  
 - *  The condition check function is passed
 - *  a pointer to a random number r between 0 and rand_modulo, a pointer to the
 - *  current node index i, and the node pointer n. This function should return true
 - *  if a connection attempt to the node should be made.
 - *  
 - *  @param mesh               A pointer to the mesh structure
 - *  @param rand_modulo        Random index is selected between 0 and rand_modulo
 - *  @cond_check               A function pointer. This function should return true
 - *                    if a connection attempt to the node should be made
 - */
 -static void cond_add_connection(meshlink_handle_t *mesh, int rand_modulo, bool (*cond_check)(int*, int*, node_t*)) {
 -      int r = rand() % rand_modulo;
 -      int i = 0;
 -
 -      for splay_each(node_t, n, mesh->nodes) {
 -              /* skip nodes that do not pass condition check */
 -              if(!(*cond_check)(&i, &r, n))
 -                      continue;
 -
 -              /* check if there is already a connection attempt to this node */
 -              bool found = false;
 -              for list_each(outgoing_t, outgoing, mesh->outgoings) {
 -                      if(!strcmp(outgoing->name, n->name)) {
 -                              found = true;
 -                              break;
 -                      }
 -              }
 +// devclass asc, last_connect_try desc
 +static int node_compare_devclass_asc_last_connect_try_desc(const void *a, const void *b)
 +{
 +      const node_t *na = a, *nb = b;
  
 -              if(!found) {
 -                      //TODO: if the node is blacklisted the connection will not happen, but
 -                      //the user will read this debug message "Autoconnecting to %s" that is misleading
 -                      logger(mesh, MESHLINK_INFO, "Autoconnecting to %s", n->name);
 -                      outgoing_t *outgoing = xzalloc(sizeof *outgoing);
 -                      outgoing->mesh = mesh;
 -                      outgoing->name = xstrdup(n->name);
 -                      list_insert_tail(mesh->outgoings, outgoing);
 -                      setup_outgoing_connection(mesh, outgoing);
 -              }
 -              break;
 -      }
 +      if(na->devclass < nb->devclass)
 +              { return -1; }
 +
 +      if(na->devclass > nb->devclass)
 +              { return 1; }
 +
 +      if(na->last_connect_try == nb->last_connect_try)
 +              return 0;
 +
 +      if(nb->last_connect_try == 0 || na->last_connect_try < nb->last_connect_try)
 +              return -1;
 +
 +      if(na->last_connect_try == 0 || na->last_connect_try > nb->last_connect_try)
 +              return 1;
 +
 +      return 0;
  }
  
 -static bool found_random_node(int *i, int *r, node_t *n) {
 -      if((*i)++ != *r)
 -              return false;
 +// last_connect_try desc
 +static int node_compare_last_connect_try_desc(const void *a, const void *b)
 +{
 +      const node_t *na = a, *nb = b;
 +
 +      if(na->last_connect_try == nb->last_connect_try)
 +              return 0;
 +
 +      if(nb->last_connect_try == 0 || na->last_connect_try < nb->last_connect_try)
 +              return -1;
  
 -      if(n->connection)
 -              return false;
 -      
 -      return true;
 +      if(na->last_connect_try == 0 || na->last_connect_try > nb->last_connect_try)
 +              return 1;
 +
 +      return 0;
  }
  
 -static bool found_random_unreachable_node(int *i, int *r, node_t *n) {
 -      if(n->status.reachable)
 -              return false;
 -      
 -      if((*i)++ != *r)
 -              return false;
 +// devclass desc
 +static int node_compare_devclass_desc(const void *a, const void *b)
 +{
 +      const node_t *na = a, *nb = b;
 +
 +      if(na->devclass < nb->devclass)
 +              { return -1; }
  
 -      if(n->connection)
 -              return false;
 +      if(na->devclass > nb->devclass)
 +              { return 1; }
  
 -      return true;
 +      return 0;
  }
  
 +
 +/*
 +
 +
 +autoconnect()
 +{
 +      timeout = 5
 +
 +      // find the best one for initial connect
 +
 +      if cur < min
 +              newcon =
 +                      first from nodes
 +                              where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
 +                              order by dclass asc, last_connection desc
 +              if newcon
 +                      timeout = 0
 +                      goto connect
 +
 +
 +      // find better nodes to connect to: in case we have less than min connections within [BACKBONE, i] and there are nodes which we are not connected to within the range
 +
 +      if min <= cur < max
 +              j = 0
 +              for i = BACKBONE to my.dclass
 +                      j += count(from connections where node.dclass = i)
 +                      if j < min
 +                              newcon =
 +                                      first from nodes
 +                                              where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
 +                                              order by last_connection desc
 +                              if newcon
 +                                      goto connect
 +                      else
 +                              break
 +
 +
 +      // heal partitions
 +
 +      if min <= cur < max
 +              newcon =
 +                      first from nodes
 +                              where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
 +                              order by dclass asc, last_connection desc
 +              if newcon
 +                      goto connect
 +
 +
 +      // connect
 +
 +connect:
 +      if newcon
 +              connect newcon
 +
 +
 +      // disconnect outgoing connections in case we have more than min connections within [BACKBONE, i] and there are nodes which we are connected to within the range [i, PORTABLE]
 +
 +      if min < cur <= max
 +              j = 0
 +              for i = BACKBONE to my.dclass
 +                      j += count(from connections where node.dclass = i)
 +                      if min < j
 +                              delcon =
 +                                      first from nodes
 +                                              where dclass >= i and outgoing_connection
 +                                              order by dclass desc
 +                              if disconnect
 +                                      goto disconnect
 +                              else
 +                                      break
 +
 +
 +      // disconnect connections in case we have more than enough connections
 +
 +      if max < cur
 +              delcon =
 +                      first from nodes
 +                              where outgoing_connection
 +                              order by dclass desc
 +              goto disconnect
 +
 +      // disconnect
 +
 +disconnect
 +      if delcon
 +              disconnect delcon
 +
 +
 +      // next iteration
 +      next (timeout, autoconnect)
 +
 +}
 +
 +
 + */
 +
 +
  static void periodic_handler(event_loop_t *loop, void *data) {
        meshlink_handle_t *mesh = loop->data;
  
  
        int timeout = 5;
  
 -      /* If AutoConnect is set, check if we need to make or break connections. */
 +      /* Check if we need to make or break connections. */
 +
 +      if(mesh->nodes->count > 1) {
  
 -      if(autoconnect && mesh->nodes->count > 1) {
 -              /* Count number of active connections */
 -              int nc = 0;
 -              for list_each(connection_t, c, mesh->connections) {
 -                      if(c->status.active)
 -                              nc++;
 +              logger(mesh, MESHLINK_INFO, "--- autoconnect begin ---");
 +
 +
 +              int retry_timeout = min(mesh->nodes->count * 5, 60);
 +
 +              // connect disconnect nodes
 +
 +              node_t* connect_to = NULL;
 +              node_t* disconnect_from = NULL;
 +
 +
 +              // get cur_connects
 +
 +              int cur_connects = 0;
 +
 +              for list_each(connection_t, c, mesh->connections)
 +              {
 +                      if(!c->status.remove_unused)
 +                      {
 +                              cur_connects += 1;
 +                      }
                }
  
 -              /* Count number of unreachable nodes */
 -              int num_unreachable = 0;
 -              for splay_each(node_t, n, mesh->nodes) {
 -                      if(!n->status.reachable)
 -                              num_unreachable++;
 +              logger(mesh, MESHLINK_INFO, "* cur_connects = %d", cur_connects);
 +
 +
 +              // get min_connects and max_connects
 +
 +              assert(mesh->devclass >= 0 && mesh->devclass <= _DEV_CLASS_MAX);
 +
 +              int min_connects = dev_class_traits[mesh->devclass].min_connects;
 +              int max_connects = dev_class_traits[mesh->devclass].max_connects;
 +
 +              logger(mesh, MESHLINK_INFO, "* min_connects = %d", min_connects);
 +              logger(mesh, MESHLINK_INFO, "* max_connects = %d", max_connects);
 +
 +
 +              // find the best one for initial connect
 +
 +              if(cur_connects < min_connects)
 +              {
 +                      splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_last_connect_try_desc, NULL);
 +
 +                      for splay_each(node_t, n, mesh->nodes)
 +                      {
 +                              if(n->devclass <= mesh->devclass && !n->connection && (n->last_connect_try == 0 || (time(NULL) - n->last_connect_try) > retry_timeout))
 +                                      { splay_insert(nodes, n); }
 +                      }
 +
 +                      if(nodes->head)
 +                      {
 +                              logger(mesh, MESHLINK_INFO, "* found best one for initial connect");
 +
 +                              //timeout = 0;
 +                              connect_to = (node_t*)nodes->head->data;
 +                      }
 +
 +                      splay_free_tree(nodes);
                }
  
 -              if(nc < autoconnect) {
 -                      /* Not enough active connections, try to add one.
 -                         Choose a random node, if we don't have a connection to it,
 -                         and we are not already trying to make one, create an
 -                         outgoing connection to this node.
 -                      */
 -                      cond_add_connection(mesh, mesh->nodes->count, &found_random_node);
 -              } else if(num_unreachable > 0) {
 -                      /* Min number of connections established. Now try
 -                         to connect to some unreachable nodes to attempt
 -                         to heal possible partitions.
 -                      */
 -                      cond_add_connection(mesh, num_unreachable, &found_random_unreachable_node);
 +
 +              // find better nodes to connect to
 +
 +              if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects)
 +              {
 +                      unsigned int connects = 0;
 +
 +                      for(int devclass = 0; devclass <= mesh->devclass; ++devclass)
 +                      {
 +                              for list_each(connection_t, c, mesh->connections)
 +                              {
 +                                      if(!c->status.remove_unused && c->node && c->node->devclass == devclass)
 +                                              { connects += 1; }
 +                              }
 +
 +                              if( connects < min_connects )
 +                              {
 +                                      splay_tree_t *nodes = splay_alloc_tree(node_compare_last_connect_try_desc, NULL);
 +
 +                                      for splay_each(node_t, n, mesh->nodes)
 +                                      {
 +                                              if(n->devclass == devclass && !n->connection && (n->last_connect_try == 0 || (time(NULL) - n->last_connect_try) > retry_timeout))
 +                                                      { splay_insert(nodes, n); }
 +                                      }
 +
 +                                      if(nodes->head)
 +                                      {
 +                                              logger(mesh, MESHLINK_INFO, "* found better node");
 +                                              connect_to = (node_t*)nodes->head->data;
 +
 +                                              splay_free_tree(nodes);
 +                                              break;
 +                                      }
 +
 +                                      splay_free_tree(nodes);
 +                              }
 +                              else
 +                                      { break; }
 +                      }
                }
 -              
 -              if(nc > autoconnect) {
 -                      /* Too many active connections, try to remove one.
 -                         Choose a random outgoing connection to a node
 -                         that has at least one other connection.
 -                      */
 -                      int r = rand() % nc;
 -                      int i = 0;
 -
 -                      for list_each(connection_t, c, mesh->connections) {
 -                              if(!c->status.active)
 -                                      continue;
  
 -                              if(i++ != r)
 -                                      continue;
  
 -                              if(!c->outgoing || !c->node || c->node->edge_tree->count < 2)
 +              // heal partitions
 +
 +              if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects)
 +              {
 +                      splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_last_connect_try_desc, NULL);
 +
 +                      for splay_each(node_t, n, mesh->nodes)
 +                      {
 +                              if(n->devclass <= mesh->devclass && !n->status.reachable && (n->last_connect_try == 0 || (time(NULL) - n->last_connect_try) > retry_timeout))
 +                                      { splay_insert(nodes, n); }
 +                      }
 +
 +                      if(nodes->head)
 +                      {
 +                              logger(mesh, MESHLINK_INFO, "* try to heal partition");
 +                              connect_to = (node_t*)nodes->head->data;
 +                      }
 +
 +                      splay_free_tree(nodes);
 +              }
 +
 +
 +              // perform connect
 +
 +              if(connect_to && !connect_to->connection)
 +              {
 +                      /* check if there is already a connection attempt to this node */
 +                      bool found = false;
 +                      for list_each(outgoing_t, outgoing, mesh->outgoings) {
 +                              if(!strcmp(outgoing->name, connect_to->name)) {
 +                                      found = true;
                                        break;
 +                              }
 +                      }
  
 -                              logger(mesh, MESHLINK_INFO, "Autodisconnecting from %s", c->name);
 -                              list_delete(mesh->outgoings, c->outgoing);
 -                              c->outgoing = NULL;
 -                              terminate_connection(mesh, c, c->status.active);
 -                              break;
 +                      if(!found)
 +                      {
 +                              logger(mesh, MESHLINK_INFO, "Autoconnecting to %s", connect_to->name);
 +                              outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
 +                              outgoing->mesh = mesh;
 +                              outgoing->name = xstrdup(connect_to->name);
 +                              list_insert_tail(mesh->outgoings, outgoing);
 +                              setup_outgoing_connection(mesh, outgoing);      
                        }
                }
  
 -              if(nc >= autoconnect) {
 -                      /* If we have enough active connections,
 -                         remove any pending outgoing connections.
 -                         Do not remove pending connections to unreachable
 -                         nodes.
 -                      */
 -                      node_t *o_node = NULL;
 -                      for list_each(outgoing_t, o, mesh->outgoings) {
 -                              o_node = lookup_node(mesh, o->name);
 -                              /* o_node is NULL if it is not part of the graph yet */
 -                              if(!o_node || !o_node->status.reachable)
 -                                      continue;
  
 -                              bool found = false;
 -                              for list_each(connection_t, c, mesh->connections) {
 -                                      if(c->outgoing == o) {
 -                                              found = true;
 -                                              break;
 -                                      }
 +              // disconnect suboptimal outgoing connections
 +
 +              if(min_connects < cur_connects && cur_connects <= max_connects)
 +              {
 +                      unsigned int connects = 0;
 +
 +                      for(int devclass = 0; devclass <= mesh->devclass; ++devclass)
 +                      {
 +                              for list_each(connection_t, c, mesh->connections)
 +                              {
 +                                      if(!c->status.remove_unused && c->node && c->node->devclass == devclass)
 +                                              { connects += 1; }
                                }
 -                              if(!found) {
 -                                      logger(mesh, MESHLINK_INFO, "Cancelled outgoing connection to %s", o->name);
 -                                      /* The node variable is leaked in from using the list_each macro.
 -                                         The o variable could be used, but using node directly
 -                                         is more efficient.
 -                                      */
 -                                      list_delete_node(mesh->outgoings, node);
 +
 +                              if( min_connects < connects )
 +                              {
 +                                      splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
 +
 +                                      for list_each(connection_t, c, mesh->connections)
 +                                      {
 +                                              if(!c->status.remove_unused && c->outgoing && c->node && c->node->devclass >= devclass)
 +                                                      { splay_insert(nodes, c->node); }
 +                                      }
 +
 +                                      if(nodes->head)
 +                                      {
 +                                              logger(mesh, MESHLINK_INFO, "* disconnect suboptimal outgoing connection");
 +                                              disconnect_from = (node_t*)nodes->head->data;
 +                                      }
 +
 +                                      splay_free_tree(nodes);
 +                                      break;
                                }
                        }
                }
  
 -              if (nc + mesh->outgoings->count < min(autoconnect, mesh->nodes->count - 1))
 -                      timeout = 0;
 +
 +              // disconnect connections (too many connections)
 +
 +              if(!disconnect_from && max_connects < cur_connects)
 +              {
 +                      splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
 +
 +                      for list_each(connection_t, c, mesh->connections)
 +                      {
 +                              if(!c->status.remove_unused && c->node)
 +                                      { splay_insert(nodes, c->node); }
 +                      }
 +
 +                      if(nodes->head)
 +                      {
 +                              logger(mesh, MESHLINK_INFO, "* disconnect connection (too many connections");
 +
 +                              //timeout = 0;
 +                              disconnect_from = (node_t*)nodes->head->data;
 +                      }
 +
 +                      splay_free_tree(nodes);
 +              }
 +
 +
 +              // perform disconnect
 +
 +              if(disconnect_from && disconnect_from->connection)
 +              {
 +                      logger(mesh, MESHLINK_INFO, "Autodisconnecting from %s", disconnect_from->connection->name);
 +                      list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
 +                      disconnect_from->connection->outgoing = NULL;
 +                      terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
 +              }
 +
 +
 +              // done!
 +
 +              logger(mesh, MESHLINK_INFO, "--- autoconnect end ---");
        }
  
        timeout_set(&mesh->loop, data, &(struct timeval){timeout, rand() % 100000});
@@@ -576,7 -355,7 +576,7 @@@ int main_loop(meshlink_handle_t *mesh) 
        mesh->datafromapp.signum = 0;
        signal_add(&(mesh->loop),&(mesh->datafromapp), (signal_cb_t)meshlink_send_from_queue,mesh, mesh->datafromapp.signum);
  
-       if(!event_loop_run(&mesh->loop)) {
+       if(!event_loop_run(&(mesh->loop), &(mesh->mesh_mutex))) {
                logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
                return 1;
        }