Use snprintf for port formatting

The buffers were all large enough for a uint16, so none of these could
actually overflow, but sprintf gives the compiler and the linters nothing
to check. Passing the destination size makes that guarantee explicit and
survives any later change to the buffers.

parse_udprelay_header writes through a caller-supplied pointer, so it
uses the MAX_PORT_STR_LEN contract its callers already allocate to.
This commit is contained in:
Max Lv
2026-08-19 18:27:19 +08:00
parent 98915c7828
commit 06bbf3d86c
2 changed files with 8 additions and 8 deletions
+5 -5
View File
@@ -396,7 +396,7 @@ server_handshake(EV_P_ ev_io *w, buffer_t *buf)
LOGI("inet_ntop(AF_INET): %s", strerror(errno));
ip[0] = '\0';
}
sprintf(port, "%d", p);
snprintf(port, sizeof(port), "%d", p);
}
} else if (atyp == SOCKS5_ATYP_DOMAIN) {
if (buf->len < request_len + 1) {
@@ -414,7 +414,7 @@ server_handshake(EV_P_ ev_io *w, buffer_t *buf)
uint16_t p = load16_be(buf->data + request_len + 1 + name_len);
memcpy(host, buf->data + request_len + 1, name_len);
host[name_len] = '\0';
sprintf(port, "%d", p);
snprintf(port, sizeof(port), "%d", p);
}
} else if (atyp == SOCKS5_ATYP_IPV6) {
size_t in6_addr_len = sizeof(struct in6_addr);
@@ -431,7 +431,7 @@ server_handshake(EV_P_ ev_io *w, buffer_t *buf)
LOGI("inet_ntop(AF_INET6): %s", strerror(errno));
ip[0] = '\0';
}
sprintf(port, "%d", p);
snprintf(port, sizeof(port), "%d", p);
}
} else {
LOGE("unsupported addrtype: %d", request->atyp);
@@ -2079,8 +2079,8 @@ _start_ss_local_server(profile_t profile, ss_local_callback callback, void *udat
char local_port_str[16];
char remote_port_str[16];
sprintf(local_port_str, "%d", local_port);
sprintf(remote_port_str, "%d", remote_port);
snprintf(local_port_str, sizeof(local_port_str), "%d", local_port);
snprintf(remote_port_str, sizeof(remote_port_str), "%d", remote_port);
#ifdef __MINGW32__
winsock_init();
+3 -3
View File
@@ -328,7 +328,7 @@ parse_udprelay_header(const char *buf, const size_t buf_len,
}
if (port != NULL) {
sprintf(port, "%d", load16_be(buf + offset));
snprintf(port, MAX_PORT_STR_LEN, "%d", load16_be(buf + offset));
}
offset += 2;
@@ -351,14 +351,14 @@ get_addr_str(const struct sockaddr *sa, bool has_port)
memcpy(&sa_in, sa, sizeof(struct sockaddr_in));
inet_ntop(AF_INET, &sa_in.sin_addr, addr, INET_ADDRSTRLEN);
p = ntohs(sa_in.sin_port);
sprintf(port, "%d", p);
snprintf(port, sizeof(port), "%d", p);
break;
case AF_INET6:
memcpy(&sa_in6, sa, sizeof(struct sockaddr_in6));
inet_ntop(AF_INET6, &sa_in6.sin6_addr, addr, INET6_ADDRSTRLEN);
p = ntohs(sa_in6.sin6_port);
sprintf(port, "%d", p);
snprintf(port, sizeof(port), "%d", p);
break;
default: