X-Git-Url: http://git.meshlink.io/?a=blobdiff_plain;f=src%2Fmeshlink.c;h=c6b14b8f043c1b0bdb4c38b6db8aa687651659b7;hb=e306efba0aa513ae498b84b7f383b05365022092;hp=07c518e0dd8c8c112aea2f85a84a756947998005;hpb=18c0a32a4de44adfeee6be42d1c1ae231d093cbf;p=meshlink diff --git a/src/meshlink.c b/src/meshlink.c index 07c518e0..c6b14b8f 100644 --- a/src/meshlink.c +++ b/src/meshlink.c @@ -537,26 +537,52 @@ static bool try_bind(int port) { return false; } - //while(ai) { + bool success = false; + for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) { - int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP); + /* Try to bind to TCP. */ - if(!fd) { - freeaddrinfo(ai); - return false; + int tcp_fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP); + + if(tcp_fd == -1) { + continue; } - int result = bind(fd, aip->ai_addr, aip->ai_addrlen); - closesocket(fd); + int result = bind(tcp_fd, aip->ai_addr, aip->ai_addrlen); + closesocket(tcp_fd); if(result) { - freeaddrinfo(ai); - return false; + if(errno == EADDRINUSE) { + /* If this port is in use for any address family, avoid it. */ + success = false; + break; + } else { + continue; + } } + + /* If TCP worked, then we require that UDP works as well. */ + + int udp_fd = socket(aip->ai_family, SOCK_DGRAM, IPPROTO_UDP); + + if(udp_fd == -1) { + success = false; + break; + } + + result = bind(udp_fd, aip->ai_addr, aip->ai_addrlen); + closesocket(udp_fd); + + if(result) { + success = false; + break; + } + + success = true; } freeaddrinfo(ai); - return true; + return success; } static int check_port(meshlink_handle_t *mesh) { @@ -1558,9 +1584,6 @@ static void *meshlink_main_loop(void *arg) { } bool meshlink_start(meshlink_handle_t *mesh) { - assert(mesh->self); - assert(mesh->private_key); - if(!mesh) { meshlink_errno = MESHLINK_EINVAL; return false; @@ -1570,6 +1593,8 @@ bool meshlink_start(meshlink_handle_t *mesh) { pthread_mutex_lock(&mesh->mutex); + assert(mesh->self); + assert(mesh->private_key); assert(mesh->self->ecdsa); assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32)); @@ -2279,7 +2304,7 @@ bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void * } bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) { - if(!mesh || !data || !len || !signature) { + if(!mesh || !source || !data || !len || !signature) { meshlink_errno = MESHLINK_EINVAL; return false; }