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; struct addrinfo *infos;
int ret = getaddrinfo(node, NULL, NULL, &infos); int ret = getaddrinfo(node, NULL, NULL, &infos);
*res = NULL;
if (ret != 0) { if (ret != 0) {
return -1; return -1;
} }
// Used to avoid malloc parameter overflow
const size_t MAX_COUNT = MIN(SIZE_MAX, INT32_MAX) / sizeof(IP_Port);
struct addrinfo *cur; struct addrinfo *cur;
int32_t count = 0;
int count = 0; for (cur = infos; count < MAX_COUNT && cur != NULL; cur = cur->ai_next) {
for (cur = infos; count < INT32_MAX && cur != NULL; cur = cur->ai_next) {
if (cur->ai_socktype && type > 0 && cur->ai_socktype != type) { if (cur->ai_socktype && type > 0 && cur->ai_socktype != type) {
continue; continue;
} }
@ -1234,8 +1236,10 @@ int32_t net_getipport(const char *node, IP_Port **res, int type)
count++; count++;
} }
if (count == INT32_MAX) { assert(count <= MAX_COUNT);
return -1;
if (count == 0) {
return 0;
} }
*res = (IP_Port *)malloc(sizeof(IP_Port) * count); *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) * Skip all addresses with socktype != type (use type = -1 to get all addresses)
* To correctly deallocate array memory use net_freeipport() * 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); int32_t net_getipport(const char *node, IP_Port **res, int type);