Skip to content

Commit 9cca6ee

Browse files
authored
Merge branch 'main' into new_cmake_options
2 parents ee5282f + 59dcd5b commit 9cca6ee

11 files changed

Lines changed: 637 additions & 33 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ Increment the:
1515

1616
## [Unreleased]
1717

18+
* [BENCHMARK] Add multi-threaded base2 exponential histogram benchmarks
19+
[#4319](https://github.com/open-telemetry/opentelemetry-cpp/pull/4319)
20+
1821
* [BUILD] Add missing opentelemetry_proto dependency to otlp_recordable
1922
pkg-config
2023
[#4316](https://github.com/open-telemetry/opentelemetry-cpp/pull/4316)
@@ -26,6 +29,9 @@ Increment the:
2629
* [CODE HEALTH] Move remaining API test helpers into anonymous namespaces
2730
[#4301](https://github.com/open-telemetry/opentelemetry-cpp/pull/4301)
2831

32+
* [BUG] Make SocketAddr string parsing safe and reject malformed addresses
33+
[#4292](https://github.com/open-telemetry/opentelemetry-cpp/pull/4292)
34+
2935
* [BUG] Fix use-after-free when an HTTP handler closes the connection
3036
[#4289](https://github.com/open-telemetry/opentelemetry-cpp/pull/4289)
3137

‎ext/BUILD‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,10 @@ package(default_visibility = ["//visibility:public"])
88
cc_library(
99
name = "headers",
1010
hdrs = glob(["include/**/*.h"]),
11+
linkopts = select({
12+
# socket_tools.h calls Winsock; declare it on the interface so consumers link it too.
13+
"//bazel:windows": ["-DEFAULTLIB:Ws2_32.lib"],
14+
"//conditions:default": [],
15+
}),
1116
strip_include_prefix = "include",
1217
)

‎ext/CMakeLists.txt‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@ target_include_directories(
1010
set_target_properties(opentelemetry_ext PROPERTIES EXPORT_NAME "ext")
1111
target_link_libraries(opentelemetry_ext INTERFACE opentelemetry_api)
1212

13+
# The embedded HTTP server headers (socket_tools.h) call Winsock, so declare the
14+
# dependency on the interface target. MSVC also autolinks via #pragma
15+
# comment(lib), but MinGW/GCC ignore that, so consumers there would otherwise
16+
# fail to resolve inet_pton/WSAStartup.
17+
if(WIN32)
18+
target_link_libraries(opentelemetry_ext INTERFACE ws2_32)
19+
endif()
20+
1321
otel_add_component(
1422
COMPONENT
1523
ext_common

‎ext/include/opentelemetry/ext/http/server/socket_tools.h‎

Lines changed: 86 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
// # include <windows.h>
2323

2424
# include <winsock2.h>
25+
# include <ws2tcpip.h> // inet_pton
2526

2627
// TODO: consider NOMINMAX
2728
# undef min
@@ -181,46 +182,85 @@ struct SocketAddr
181182
inet4.sin_addr.s_addr = htonl(addr);
182183
}
183184

185+
/// Parses an IPv4 address in "host" or "host:port" form. Host parsing follows the platform's
186+
/// inet_pton(AF_INET), which requires four decimal components; a port, when present, must be
187+
/// decimal digits only in the range 0..65535, and an omitted port is represented as 0. Invalid
188+
/// input leaves the address at AF_UNSPEC, for which port() returns -1.
184189
SocketAddr(char const *addr)
185190
{
186-
#ifdef _WIN32
187-
INT addrlen = sizeof(m_data);
188-
WCHAR buf[200];
189-
for (int i = 0; i < sizeof(buf) && addr[i]; i++)
191+
// One parser for every platform: inet_pton (Winsock provides it since Vista) plus a strict
192+
// decimal port. This avoids WSAStringToAddress, whose grammar and default-component filling
193+
// differ from the POSIX path. Parse into a local sockaddr_in and commit with memcpy only on
194+
// success, which keeps m_data at AF_UNSPEC on failure and avoids accessing the sockaddr
195+
// storage through a sockaddr_in glvalue (an alignment/type-access issue tracked in #4307).
196+
if (addr == nullptr)
190197
{
191-
buf[i] = addr[i];
198+
LOG_WARN("SocketAddr: cannot parse a null address");
199+
return; // m_data is already AF_UNSPEC, so port() reports -1.
192200
}
193-
buf[199] = L'\0';
194-
::WSAStringToAddressW(buf, AF_INET, nullptr, &m_data, &addrlen);
195-
#else
196-
sockaddr_in &inet4 = reinterpret_cast<sockaddr_in &>(m_data);
197-
inet4.sin_family = AF_INET;
198-
char const *colon = strchr(addr, ':');
199-
if (colon)
201+
202+
sockaddr_in parsed{};
203+
parsed.sin_family = AF_INET;
204+
205+
char const *colon = strchr(addr, ':');
206+
char const *hostEnd = colon ? colon : addr + strlen(addr);
207+
ptrdiff_t const hostLength = hostEnd - addr;
208+
209+
// Reject a host that would not fit rather than truncating it into a different valid address
210+
// (for example "255.255.255.2559" would otherwise become "255.255.255.255"). No dotted-quad
211+
// exceeds 15 characters.
212+
bool ok = (hostLength >= 1 && hostLength <= 15);
213+
if (ok)
200214
{
201-
char *portEnd = nullptr;
202-
errno = 0;
203-
auto const parsed = std::strtol(colon + 1, &portEnd, 10);
204-
// Accept only a converted, in-range port value; fall back to 0 otherwise.
205-
if (errno == 0 && portEnd != colon + 1 && parsed >= 0 && parsed <= 65535)
215+
char host[16];
216+
memcpy(host, addr, static_cast<size_t>(hostLength));
217+
host[hostLength] = '\0';
218+
ok = (::inet_pton(AF_INET, host, &parsed.sin_addr) == 1);
219+
}
220+
221+
// Port: decimal digits only, with overflow checked before it can wrap. strtol would also
222+
// accept a leading sign or whitespace and depend on the locale.
223+
if (ok && colon)
224+
{
225+
char const *p = colon + 1;
226+
unsigned int port = 0;
227+
if (*p == '\0')
206228
{
207-
inet4.sin_port = htons(static_cast<uint16_t>(parsed));
229+
ok = false; // empty port, e.g. "127.0.0.1:"
208230
}
209-
else
231+
while (ok && *p != '\0')
232+
{
233+
if (*p < '0' || *p > '9')
234+
{
235+
ok = false;
236+
break;
237+
}
238+
unsigned int const digit = static_cast<unsigned int>(*p - '0');
239+
if (port > (65535u - digit) / 10u)
240+
{
241+
ok = false; // would exceed 65535
242+
break;
243+
}
244+
port = port * 10u + digit;
245+
++p;
246+
}
247+
if (ok)
210248
{
211-
inet4.sin_port = 0;
249+
parsed.sin_port = htons(static_cast<uint16_t>(port));
212250
}
213-
char buf[16];
214-
memcpy(buf, addr, (std::min<ptrdiff_t>)(15, colon - addr));
215-
buf[15] = '\0';
216-
::inet_pton(AF_INET, buf, &inet4.sin_addr);
251+
}
252+
253+
if (ok)
254+
{
255+
memcpy(&m_data, &parsed, sizeof(parsed));
217256
}
218257
else
219258
{
220-
inet4.sin_port = 0;
221-
::inet_pton(AF_INET, addr, &inet4.sin_addr);
259+
// Leave m_data at AF_UNSPEC; port() returns -1 so callers can tell a parse failure from a
260+
// real endpoint, including the legitimate ":0". Do not echo the raw input, which may be
261+
// arbitrarily long.
262+
LOG_WARN("SocketAddr: cannot parse address");
222263
}
223-
#endif
224264
}
225265

226266
operator sockaddr *() { return &m_data; }
@@ -232,7 +272,10 @@ struct SocketAddr
232272
switch (m_data.sa_family)
233273
{
234274
case AF_INET: {
235-
sockaddr_in const &inet4 = reinterpret_cast<sockaddr_in const &>(m_data);
275+
// Copy out rather than binding a sockaddr_in glvalue to sockaddr storage, which is an
276+
// alignment/type-access issue (see the constructor and #4307).
277+
sockaddr_in inet4{};
278+
memcpy(&inet4, &m_data, sizeof(inet4));
236279
return ntohs(inet4.sin_port);
237280
}
238281

@@ -248,8 +291,9 @@ struct SocketAddr
248291
switch (m_data.sa_family)
249292
{
250293
case AF_INET: {
251-
sockaddr_in const &inet4 = reinterpret_cast<sockaddr_in const &>(m_data);
252-
u_long addr = ntohl(inet4.sin_addr.s_addr);
294+
sockaddr_in inet4{};
295+
memcpy(&inet4, &m_data, sizeof(inet4));
296+
u_long addr = ntohl(inet4.sin_addr.s_addr);
253297
os << (addr >> 24) << '.' << ((addr >> 16) & 255) << '.' << ((addr >> 8) & 255) << '.'
254298
<< (addr & 255);
255299
os << ':' << ntohs(inet4.sin_port);
@@ -263,6 +307,18 @@ struct SocketAddr
263307
}
264308
};
265309

310+
// The parser memcpys a sockaddr_in into m_data, and the socket syscalls pass sizeof(SocketAddr)
311+
// as the address length. This wrapper is IPv4-only, so require sockaddr and sockaddr_in to have
312+
// the exact same size rather than trusting every ABI: passing an address length that is too large
313+
// for the family is a documented EINVAL for connect()/bind(). Exact equality also keeps the memcpy
314+
// safe. Together with the assertion below, sizeof(SocketAddr) == sizeof(sockaddr_in).
315+
static_assert(sizeof(sockaddr) == sizeof(sockaddr_in),
316+
"SocketAddr is IPv4-only: sockaddr and sockaddr_in must have identical size");
317+
static_assert(offsetof(sockaddr, sa_family) == offsetof(sockaddr_in, sin_family),
318+
"sockaddr and sockaddr_in must place the address family at the same offset");
319+
static_assert(sizeof(SocketAddr) == sizeof(sockaddr),
320+
"SocketAddr must add no storage beyond its sockaddr, since syscalls use its size");
321+
266322
/// <summary>
267323
/// Encapsulation of a socket (non-exclusive ownership)
268324
/// </summary>

‎ext/test/http/BUILD‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,20 @@
33

44
load("@rules_cc//cc:cc_test.bzl", "cc_test")
55

6+
cc_test(
7+
name = "socket_tools_test",
8+
srcs = [
9+
"socket_tools_test.cc",
10+
],
11+
# ws2_32 is an interface linkopt of //ext:headers, so it is inherited here rather than
12+
# relinked, which also lets the test verify the public target's usage requirements.
13+
tags = ["test"],
14+
deps = [
15+
"//ext:headers",
16+
"@com_google_googletest//:gtest_main",
17+
],
18+
)
19+
620
cc_test(
721
name = "curl_http_test",
822
srcs = [

‎ext/test/http/CMakeLists.txt‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,18 @@ if(OTELCPP_WITH_HTTP_CLIENT_CURL)
1414
TEST_LIST ${FILENAME})
1515
endif()
1616

17+
set(SOCKET_TOOLS_FILENAME socket_tools_test)
18+
add_executable(${SOCKET_TOOLS_FILENAME} ${SOCKET_TOOLS_FILENAME}.cc)
19+
target_link_libraries(${SOCKET_TOOLS_FILENAME} opentelemetry_ext ${GMOCK_LIB}
20+
${GTEST_BOTH_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT})
21+
# ws2_32 is now an interface dependency of opentelemetry_ext, so it is inherited
22+
# here; the test thus verifies the public target's usage requirements rather
23+
# than papering over them locally.
24+
gtest_add_tests(
25+
TARGET ${SOCKET_TOOLS_FILENAME}
26+
TEST_PREFIX ext.http.sockettools.
27+
TEST_LIST ${SOCKET_TOOLS_FILENAME})
28+
1729
set(URL_PARSER_FILENAME url_parser_test)
1830
add_executable(${URL_PARSER_FILENAME} ${URL_PARSER_FILENAME}.cc)
1931
target_link_libraries(${URL_PARSER_FILENAME} opentelemetry_ext ${GMOCK_LIB}

0 commit comments

Comments
 (0)