improve error handing in anetFDToString to avoid returning successfully with garbage.
Check for errors in inet_ntop and snprintf rather than ignore them
and return success (with garbage output).
The check for ip_len == 0 seems like dead code, removed.
@@ -541,18 +541,26 @@ int anetFdToString(int fd, char *ip, size_t ip_len, int *port, int fd_to_str_typ
} else {
if (getsockname(fd, (struct sockaddr *)&sa, &salen) == -1) goto error;
}
- if (ip_len == 0) goto error;
if (sa.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&sa;
- if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len);
+ if (ip) {
+ if (inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len) == NULL)
+ goto error;
+ }
if (port) *port = ntohs(s->sin_port);
} else if (sa.ss_family == AF_INET6) {
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa;
- if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len);
+ if (ip) {
+ if (inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len) == NULL)
+ goto error;
+ }
if (port) *port = ntohs(s->sin6_port);
} else if (sa.ss_family == AF_UNIX) {
- if (ip) snprintf(ip, ip_len, "/unixsocket");
+ if (ip) {
+ int res = snprintf(ip, ip_len, "/unixsocket");
+ if (res < 0 || (unsigned int) res >= ip_len) goto error;
+ }
if (port) *port = 0;
} else {
goto error;
