From 98d0eb964413f6cc655640f207dde4bf5f1ce89d Mon Sep 17 00:00:00 2001 From: Guus Sliepen Date: Thu, 4 Jul 2019 20:40:09 +0200 Subject: [PATCH] Prevent meshlink_join() when the joining node is already part of a mesh. --- src/meshlink.c | 10 +++++++++- test/invite-join.c | 36 ++++++++++++++++++++++++++++++++++-- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/src/meshlink.c b/src/meshlink.c index 9b13dca1..302624fc 100644 --- a/src/meshlink.c +++ b/src/meshlink.c @@ -2310,7 +2310,15 @@ bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) { //Before doing meshlink_join make sure we are not connected to another mesh if(mesh->threadstarted) { - logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n"); + logger(mesh, MESHLINK_ERROR, "Cannot join while started\n"); + meshlink_errno = MESHLINK_EINVAL; + pthread_mutex_unlock(&(mesh->mesh_mutex)); + return false; + } + + // Refuse to join a mesh if we are already part of one. We are part of one if we know at least one other node. + if(mesh->nodes->count > 1) { + logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n"); meshlink_errno = MESHLINK_EINVAL; pthread_mutex_unlock(&(mesh->mesh_mutex)); return false; diff --git a/test/invite-join.c b/test/invite-join.c index b69eb3d8..52a922a8 100644 --- a/test/invite-join.c +++ b/test/invite-join.c @@ -106,8 +106,6 @@ int main() { return 1; } - free(baz_url); - if(!meshlink_start(mesh2)) { fprintf(stderr, "Baz could not start\n"); return 1; @@ -140,6 +138,15 @@ int main() { return 1; } + // Check that an invitation cannot be used twice + + if(meshlink_join(mesh3, baz_url)) { + fprintf(stderr, "Quux could join foo's mesh using an already used invitation\n"); + return 1; + } + + free(baz_url); + // Check that nodes cannot join with expired invitations meshlink_set_invitation_timeout(mesh1, 0); @@ -151,6 +158,31 @@ int main() { free(quux_url); + // Check that existing nodes cannot join another mesh + + char *corge_url = meshlink_invite(mesh3, NULL, "corge"); + + if(!corge_url) { + fprintf(stderr, "Quux could not generate an invitation for corge\n"); + return 1; + } + + fprintf(stderr, "Invitation URL for corge: %s\n", corge_url); + + if(!meshlink_start(mesh3)) { + fprintf(stderr, "Quux could not start\n"); + return 1; + } + + meshlink_stop(mesh2); + + if(meshlink_join(mesh2, corge_url)) { + fprintf(stderr, "Bar could join twice\n"); + return 1; + } + + free(corge_url); + // Clean up. meshlink_close(mesh3); -- 2.39.5