Skip to content

Commit 6d86940

Browse files
authored
Merge branch 'main' into fix/windows-spinlock-srwlock
2 parents 357bf71 + feea622 commit 6d86940

32 files changed

Lines changed: 1228 additions & 115 deletions

File tree

‎.github/workflows/stale.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ jobs:
1313
pull-requests: write # for actions/stale to close stale PRs
1414
runs-on: ubuntu-latest
1515
steps:
16-
- uses: actions/stale@1e223db275d687790206a7acac4d1a11bd6fe629 # v10.4.0
16+
- uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0
1717
with:
1818
stale-issue-message: "This issue was marked as stale due to lack of activity."
1919
days-before-issue-stale: 60

‎CHANGELOG.md‎

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

1616
## [Unreleased]
1717

18-
* [METRICS SDK] Fix Windows metrics tail latency on the synchronous record path:
19-
`SyncMetricStorage::attribute_hashmap_lock_` now uses `std::mutex` instead of
20-
`common::SpinLockMutex`. The spin lock's final `sleep_for(1ms)` back-off is
21-
rounded up to the Windows timer quantum (~15.6 ms), so a waiter contending on a
22-
hot instrument could stall for a full quantum, inflating tail latency.
23-
`std::mutex` blocks the waiter instead. Only this one contended lock changes;
24-
the API `SpinLockMutex` and all other SDK locks are unchanged.
25-
[#4245](https://github.com/open-telemetry/opentelemetry-cpp/pull/4245)
26-
18+
* [BUILD] Run the ext_http component install test on Windows
19+
[#4326](https://github.com/open-telemetry/opentelemetry-cpp/pull/4326)
20+
21+
* [BENCHMARK] Add multi-threaded base2 exponential histogram benchmarks
22+
[#4319](https://github.com/open-telemetry/opentelemetry-cpp/pull/4319)
23+
24+
* [BUILD] Add missing opentelemetry_proto dependency to otlp_recordable
25+
pkg-config
26+
[#4316](https://github.com/open-telemetry/opentelemetry-cpp/pull/4316)
27+
2728
* [CODE HEALTH] Move SDK trace and metrics test helpers into anonymous
2829
namespaces
2930
[#4303](https://github.com/open-telemetry/opentelemetry-cpp/pull/4303)
3031

3132
* [CODE HEALTH] Move remaining API test helpers into anonymous namespaces
3233
[#4301](https://github.com/open-telemetry/opentelemetry-cpp/pull/4301)
3334

35+
* [BUG] Make SocketAddr string parsing safe and reject malformed addresses
36+
[#4292](https://github.com/open-telemetry/opentelemetry-cpp/pull/4292)
37+
38+
* [BUG] Fix use-after-free when an HTTP handler closes the connection
39+
[#4289](https://github.com/open-telemetry/opentelemetry-cpp/pull/4289)
40+
3441
* [CODE HEALTH] Move metrics storage test fixtures into anonymous namespace
3542
[#4286](https://github.com/open-telemetry/opentelemetry-cpp/pull/4286)
3643

@@ -72,6 +79,19 @@ Increment the:
7279
namespaces
7380
[#4302](https://github.com/open-telemetry/opentelemetry-cpp/pull/4302)
7481

82+
* [METRICS SDK] Fix histogram views being rejected when only
83+
`aggregation_cardinality_limit` is set
84+
[#4314](https://github.com/open-telemetry/opentelemetry-cpp/pull/4314)
85+
86+
* [METRICS SDK] Fix Windows metrics tail latency on the synchronous record path:
87+
`SyncMetricStorage::attribute_hashmap_lock_` now uses `std::mutex` instead of
88+
`common::SpinLockMutex`. The spin lock's final `sleep_for(1ms)` back-off is
89+
rounded up to the Windows timer quantum (~15.6 ms), so a waiter contending on a
90+
hot instrument could stall for a full quantum, inflating tail latency.
91+
`std::mutex` blocks the waiter instead. Only this one contended lock changes;
92+
the API `SpinLockMutex` and all other SDK locks are unchanged.
93+
[#4245](https://github.com/open-telemetry/opentelemetry-cpp/pull/4245)
94+
7595
Breaking changes:
7696

7797
* [METRICS SDK] Rename Base2 Exponential Histogram Aggregation config field

‎INSTALL.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,8 @@ build configuration.
242242
| | opentelemetry-cpp::trace |
243243
| | opentelemetry-cpp::metrics |
244244
| | opentelemetry-cpp::logs |
245+
| | opentelemetry-cpp::configuration_core (EXPERIMENTAL: Programmatic configuration) |
246+
| **configuration** | opentelemetry-cpp::configuration (EXPERIMENTAL: YAML configuration) |
245247
| **ext_common** | opentelemetry-cpp::ext |
246248
| **ext_http_curl** | opentelemetry-cpp::http_client_curl |
247249
| **ext_dll** | opentelemetry-cpp::opentelemetry_cpp |

‎ci/do_ci.ps1‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,7 @@ switch ($action) {
432432
"api",
433433
"sdk",
434434
"ext_common",
435+
"ext_http",
435436
"ext_http_curl",
436437
"exporters_in_memory",
437438
"exporters_ostream",

‎exporters/otlp/CMakeLists.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ if(OPENTELEMETRY_INSTALL)
6969
otlp_recordable
7070
"OpenTelemetry OTLP - Recordable"
7171
"OTLP recordable implementation for spans, metrics, and logs."
72-
"opentelemetry_trace opentelemetry_metrics opentelemetry_logs opentelemetry_resources"
72+
"opentelemetry_trace opentelemetry_metrics opentelemetry_logs opentelemetry_resources opentelemetry_proto"
7373
)
7474

7575
opentelemetry_add_pkgconfig(

‎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/http_server.h‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,16 @@ class HttpServer : private SocketTools::Reactor::SocketCallback
367367
m_reactor.removeSocket(conn.socket);
368368
auto connIt = m_connections.find(conn.socket);
369369
conn.socket.close();
370-
m_connections.erase(connIt);
370+
// Every caller passes a connection that is in the map. The guard keeps a broken invariant
371+
// from turning into erase(end()), and the assert keeps it from passing unnoticed in a
372+
// debug build. This does not make the function idempotent: the reactor removal and the
373+
// socket close above have already run.
374+
assert(connIt != m_connections.end());
375+
if (connIt != m_connections.end())
376+
{
377+
// Destroys the Connection that conn refers to: callers must not use conn afterwards.
378+
m_connections.erase(connIt);
379+
}
371380
}
372381

373382
void handleConnection(Connection &conn)
@@ -522,7 +531,14 @@ class HttpServer : private SocketTools::Reactor::SocketCallback
522531

523532
if (conn.state == Connection::Processing)
524533
{
525-
processRequest(conn);
534+
if (processRequest(conn) == RequestOutcome::CloseConnection)
535+
{
536+
// Mark the close as intentional so it is not reported as unexpected, then stop:
537+
// handleConnectionClosed() erases conn, so it must not be touched afterwards.
538+
conn.state = Connection::Closing;
539+
handleConnectionClosed(conn);
540+
return;
541+
}
526542

527543
std::ostringstream os;
528544
os << conn.request.protocol << ' ' << conn.response.code << ' ' << conn.response.message
@@ -736,7 +752,18 @@ class HttpServer : private SocketTools::Reactor::SocketCallback
736752
return result;
737753
}
738754

739-
void processRequest(Connection &conn)
755+
enum class RequestOutcome : std::uint8_t
756+
{
757+
SendResponse,
758+
CloseConnection
759+
};
760+
761+
/**
762+
* Run the registered handlers for a request and fill in the response.
763+
* @return CloseConnection if a handler asked for the connection to be terminated. Closing is
764+
* left to the caller, which owns the connection's lifetime.
765+
*/
766+
RequestOutcome processRequest(Connection &conn)
740767
{
741768
conn.response.message.clear();
742769
conn.response.headers.clear();
@@ -766,7 +793,7 @@ class HttpServer : private SocketTools::Reactor::SocketCallback
766793
if (conn.response.code == -1)
767794
{
768795
LOG_TRACE("HttpServer: [%s] closing by request", conn.request.client.c_str());
769-
handleConnectionClosed(conn);
796+
return RequestOutcome::CloseConnection;
770797
}
771798
}
772799

@@ -779,6 +806,8 @@ class HttpServer : private SocketTools::Reactor::SocketCallback
779806
conn.response.headers["Connection"] = (conn.keepalive ? "keep-alive" : "close");
780807
conn.response.headers["Date"] = formatTimestamp(time(nullptr));
781808
conn.response.headers["Content-Length"] = std::to_string(conn.response.body.size());
809+
810+
return RequestOutcome::SendResponse;
782811
}
783812

784813
static std::string formatTimestamp(time_t time)

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

Lines changed: 100 additions & 32 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>
@@ -776,7 +832,13 @@ struct Reactor : protected common::Thread
776832
for (int i = 0; i < result; i++)
777833
{
778834
auto it = std::find(m_sockets.begin(), m_sockets.end(), events[i].data.fd);
779-
assert(it != m_sockets.end());
835+
if (it == m_sockets.end())
836+
{
837+
// epoll_wait() fills a batch, and handling one event can remove a socket that a later
838+
// entry in the same batch still names. Such an entry is stale, and reading it->socket
839+
// would dereference end().
840+
continue;
841+
}
780842
Socket socket = it->socket;
781843
int flags = it->flags;
782844

@@ -814,7 +876,13 @@ struct Reactor : protected common::Thread
814876
struct kevent &event = m_events[i];
815877
int fd = (int)event.ident;
816878
auto it = std::find(m_sockets.begin(), m_sockets.end(), fd);
817-
assert(it != m_sockets.end());
879+
if (it == m_sockets.end())
880+
{
881+
// kevent() reports a batch, and handling one event can remove a socket that a later
882+
// entry in the same batch still names. Such an entry is stale, and reading it->socket
883+
// would dereference end().
884+
continue;
885+
}
818886
Socket socket = it->socket;
819887
int flags = it->flags;
820888

0 commit comments

Comments
 (0)