Fix network malloc(0) bug

This commit is contained in:
Diadlo 2017-03-12 09:55:28 +03:00 committed by iphydf
parent 50c526e1a5
commit f675474c08
No known key found for this signature in database
GPG Key ID: 3855DBA2D74403C9
2 changed files with 11 additions and 6 deletions

View File

@ -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);

View File

@ -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);