From a8d5274bbe2c6d048732f4224d399966b1bd3de3 Mon Sep 17 00:00:00 2001 From: Paul-Louis Ageneau Date: Fri, 19 Jan 2024 22:58:34 +0100 Subject: [PATCH] Unmap WebSocket remote IPv4-mapped IPv6 addresses --- src/impl/tcptransport.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/impl/tcptransport.cpp b/src/impl/tcptransport.cpp index d774ff4d2..b3af2c209 100644 --- a/src/impl/tcptransport.cpp +++ b/src/impl/tcptransport.cpp @@ -26,6 +26,30 @@ using namespace std::chrono_literals; using std::chrono::duration_cast; using std::chrono::milliseconds; +namespace { + +bool unmap_inet6_v4mapped(struct sockaddr *sa, socklen_t *len) { + if (sa->sa_family != AF_INET6) + return false; + + const auto *sin6 = reinterpret_cast(sa); + if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) + return false; + + struct sockaddr_in6 copy = *sin6; + sin6 = © + + auto *sin = reinterpret_cast(sa); + std::memset(sin, 0, sizeof(*sin)); + sin->sin_family = AF_INET; + sin->sin_port = sin6->sin6_port; + std::memcpy(&sin->sin_addr, reinterpret_cast(&sin6->sin6_addr) + 12, 4); + *len = sizeof(*sin); + return true; +} + +} + TcpTransport::TcpTransport(string hostname, string service, state_callback callback) : Transport(nullptr, std::move(callback)), mIsActive(true), mHostname(std::move(hostname)), mService(std::move(service)), mSock(INVALID_SOCKET) { @@ -47,6 +71,8 @@ TcpTransport::TcpTransport(socket_t sock, state_callback callback) if (::getpeername(mSock, reinterpret_cast(&addr), &addrlen) < 0) throw std::runtime_error("getsockname failed"); + unmap_inet6_v4mapped(reinterpret_cast(&addr), &addrlen); + char node[MAX_NUMERICNODE_LEN]; char serv[MAX_NUMERICSERV_LEN]; if (::getnameinfo(reinterpret_cast(&addr), addrlen, node,