From 43ffcfc3c3fcd8088a77e9a2ac9cc4013c466158 Mon Sep 17 00:00:00 2001 From: Guus Sliepen Date: Tue, 1 May 2018 14:10:45 +0200 Subject: [PATCH] Check the return value of check_port(). When initializing a new MeshLink instance, fail if there is no port available for listening. When starting an already configured instance, if no Port statement is found in the local node's host config file, select and add a new one. --- src/meshlink.c | 15 +++++++++++---- src/meshlink_internal.h | 1 + src/net_setup.c | 6 ++++-- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/meshlink.c b/src/meshlink.c index 769e52c6..d4a833ab 100644 --- a/src/meshlink.c +++ b/src/meshlink.c @@ -444,7 +444,7 @@ static bool try_bind(int port) { return true; } -static int check_port(meshlink_handle_t *mesh) { +int check_port(meshlink_handle_t *mesh) { for(int i = 0; i < 1000; i++) { int port = 0x1000 + (rand() & 0x7fff); @@ -454,7 +454,8 @@ static int check_port(meshlink_handle_t *mesh) { FILE *f = fopen(filename, "a"); if(!f) { - logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n"); + meshlink_errno = MESHLINK_ESTORAGE; + logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n"); return 0; } @@ -464,7 +465,8 @@ static int check_port(meshlink_handle_t *mesh) { } } - logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n"); + meshlink_errno = MESHLINK_ENETWORK; + logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n"); return 0; } @@ -948,10 +950,15 @@ static bool meshlink_setup(meshlink_handle_t *mesh) { if(!ecdsa_keygen(mesh)) { meshlink_errno = MESHLINK_EINTERNAL; + unlink(filename); return false; } - check_port(mesh); + if (check_port(mesh) == 0) { + meshlink_errno = MESHLINK_ENETWORK; + unlink(filename); + return false; + } return true; } diff --git a/src/meshlink_internal.h b/src/meshlink_internal.h index a727bb53..d7d4910b 100644 --- a/src/meshlink_internal.h +++ b/src/meshlink_internal.h @@ -170,6 +170,7 @@ extern void meshlink_send_from_queue(event_loop_t *el, meshlink_handle_t *mesh); extern void update_node_status(meshlink_handle_t *mesh, struct node_t *n); extern meshlink_log_level_t global_log_level; extern meshlink_log_cb_t global_log_cb; +extern int check_port(meshlink_handle_t *mesh); /// Device class traits typedef struct { diff --git a/src/net_setup.c b/src/net_setup.c index a59632cf..2cd02111 100644 --- a/src/net_setup.c +++ b/src/net_setup.c @@ -365,8 +365,10 @@ bool setup_myself(meshlink_handle_t *mesh) { read_host_config(mesh, mesh->config, name); if(!get_config_string(lookup_config(mesh->config, "Port"), &mesh->myport)) { - logger(mesh, MESHLINK_ERROR, "Port for MeshLink instance required!"); - return false; + int port = check_port(mesh); + if (port == 0) + return false; + xasprintf(&mesh->myport, "%d", port); } mesh->self->connection->options = 0; -- 2.39.5