diff --git a/toxcore/network.c b/toxcore/network.c index 69dacee4..215ab8e0 100644 --- a/toxcore/network.c +++ b/toxcore/network.c @@ -1213,16 +1213,18 @@ int32_t net_getipport(const char *node, IP_Port **res, int type) { struct addrinfo *infos; int ret = getaddrinfo(node, NULL, NULL, &infos); + *res = NULL; if (ret != 0) { return -1; } + // Used to avoid malloc parameter overflow + const size_t MAX_COUNT = MIN(SIZE_MAX, INT32_MAX) / sizeof(IP_Port); struct addrinfo *cur; + int32_t count = 0; - int count = 0; - - for (cur = infos; count < INT32_MAX && cur != NULL; cur = cur->ai_next) { + for (cur = infos; count < MAX_COUNT && cur != NULL; cur = cur->ai_next) { if (cur->ai_socktype && type > 0 && cur->ai_socktype != type) { continue; } @@ -1234,8 +1236,10 @@ int32_t net_getipport(const char *node, IP_Port **res, int type) count++; } - if (count == INT32_MAX) { - return -1; + assert(count <= MAX_COUNT); + + if (count == 0) { + return 0; } *res = (IP_Port *)malloc(sizeof(IP_Port) * count); diff --git a/toxcore/network.h b/toxcore/network.h index 92e5bbcf..28795602 100644 --- a/toxcore/network.h +++ b/toxcore/network.h @@ -389,7 +389,8 @@ int net_connect(Socket sock, IP_Port ip_port); * Skip all addresses with socktype != type (use type = -1 to get all addresses) * To correctly deallocate array memory use net_freeipport() * - * return number of elements in res array. + * return number of elements in res array + * and -1 on error. */ int32_t net_getipport(const char *node, IP_Port **res, int type);