From e01c92a5ef6127067922f74cd8dac2ba72a1ad52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?George=20Anderson=20Guimar=C3=A3es?= <571682+georgeanderson@users.noreply.github.com> Date: Tue, 11 May 2021 06:27:08 -0500 Subject: [PATCH] improve error handing in anetFDToString to avoid returning successfully with garbage. (#8678) 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. --- src/anet.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/anet.c b/src/anet.c index 04ccc540d..381dda375 100644 --- a/src/anet.c +++ b/src/anet.c @@ -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;