From b8b1e611a798f957b0fbd3ca9887ef6e5ed6d190 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Wed, 18 Nov 2026 18:00:20 -0600 Subject: [PATCH 1/7] Keep curl teardown from hanging on stalled DNS When the collector's DNS is unreachable, teardown of the curl transport could block host process exit for the system resolver timeout (tens of seconds). curl_easy_perform() does not run the progress callback while a name is resolving, so Abort() waited for the 5s connect timeout, and curl_easy_cleanup()/curl_multi_cleanup() then joined the resolver thread still blocked in getaddrinfo(). Set CURLOPT_QUICK_EXIT on every handle, and run modern-libcurl transfers on a private multi handle with CURLMOPT_QUICK_EXIT, polling the abort flag every 100ms. Option ids are passed numerically so a runtime libcurl newer than the build headers still receives them. A Linux unit test interposes getaddrinfo() to stall deterministically; it hangs 60s without this change. Files changed: - lib/http/HttpClient_Curl.hpp - tests/unittests/CMakeLists.txt - tests/unittests/HttpClientCurlTests.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ff620832-ec83-4315-b3e0-6f5d825d45e1 --- lib/http/HttpClient_Curl.hpp | 86 +++++++++++++++++- tests/unittests/CMakeLists.txt | 4 + tests/unittests/HttpClientCurlTests.cpp | 114 ++++++++++++++++++++++++ 3 files changed, 203 insertions(+), 1 deletion(-) diff --git a/lib/http/HttpClient_Curl.hpp b/lib/http/HttpClient_Curl.hpp index eac40ad13..c5d6bf7b6 100644 --- a/lib/http/HttpClient_Curl.hpp +++ b/lib/http/HttpClient_Curl.hpp @@ -45,6 +45,18 @@ #define HTTP_CONN_TIMEOUT 5L +// libcurl option ids are ABI-stable and never reused. Pass these by number so +// a runtime libcurl newer than the build headers still receives them; an +// older runtime rejects an unknown id without side effects. +#define MATSDK_CURLOPT_QUICK_EXIT static_cast(CURLOPTTYPE_LONG + 322) // libcurl 7.87.0 +#define MATSDK_CURLMOPT_QUICK_EXIT static_cast(CURLOPTTYPE_LONG + 21) // libcurl 8.20.0 +#if LIBCURL_VERSION_NUM >= 0x075700 +static_assert(MATSDK_CURLOPT_QUICK_EXIT == CURLOPT_QUICK_EXIT, "CURLOPT_QUICK_EXIT id changed"); +#endif +#if LIBCURL_VERSION_NUM >= 0x081400 +static_assert(MATSDK_CURLMOPT_QUICK_EXIT == CURLMOPT_QUICK_EXIT, "CURLMOPT_QUICK_EXIT id changed"); +#endif + #undef TRACE #define TRACE(...) // printf @@ -337,6 +349,14 @@ class CurlHttpOperation { // With NOSIGNAL, a synchronous resolver may still prevent libcurl from // enforcing a strict deadline until the resolver call returns. + // Teardown drains every operation, and curl_easy_cleanup() otherwise + // joins a resolver thread that can stay blocked in getaddrinfo() for the + // system DNS timeout when the collector is unreachable, stalling host + // process exit. Best effort: an older runtime libcurl rejects it. + // Trade-off: a resolver thread abandoned this way runs until + // getaddrinfo() returns, and must not outlive an unloaded libcurl. + (void)curl_easy_setopt(curl, MATSDK_CURLOPT_QUICK_EXIT, 1L); + // Headers are copied into m_headersChunk during construction and the // curl_slist is kept alive until destruction, so the original map does // not need operation-lifetime storage. @@ -551,7 +571,8 @@ class CurlHttpOperation { goto cleanup; } DispatchEvent(m_usePrereqCallback ? OnConnecting : OnSending); - m_transportError = curl_easy_perform(curl); + // The legacy CONNECT_ONLY path must reuse the easy handle's connection. + m_transportError = m_usePrereqCallback ? PerformAbortable() : curl_easy_perform(curl); if(CURLE_OK != m_transportError) { DispatchEvent(!m_usePrereqCallback || m_connectionReady ? OnSendFailed : OnConnectFailed); @@ -961,6 +982,69 @@ class CurlHttpOperation { } } + /** + * Run the transfer on a private multi handle so cancellation is observed + * within one poll slice. curl_easy_perform() does not invoke the progress + * callback while a name is resolving, so an abort during a stalled DNS + * lookup would otherwise wait for the full connect timeout. + */ + CURLcode PerformAbortable() + { +#if LIBCURL_VERSION_NUM >= 0x074200 // libcurl 7.66.0: curl_multi_poll + CURLM* multi = curl_multi_init(); + if (multi == nullptr) + { + return CURLE_OUT_OF_MEMORY; + } + // From libcurl 8.20.0 resolver threads belong to the multi handle; do + // not join them. + (void)curl_multi_setopt(multi, MATSDK_CURLMOPT_QUICK_EXIT, 1L); + if (curl_multi_add_handle(multi, curl) != CURLM_OK) + { + curl_multi_cleanup(multi); + return CURLE_FAILED_INIT; + } + + CURLcode result = CURLE_FAILED_INIT; + constexpr int sliceMs = 100; + for (;;) + { + int running = 0; + if (curl_multi_perform(multi, &running) != CURLM_OK) + { + break; + } + if (running == 0) + { + int queued = 0; + while (CURLMsg* msg = curl_multi_info_read(multi, &queued)) + { + if (msg->msg == CURLMSG_DONE && msg->easy_handle == curl) + { + result = msg->data.result; + } + } + break; + } + if (isAborted.load(std::memory_order_acquire)) + { + result = CURLE_ABORTED_BY_CALLBACK; + break; + } + if (curl_multi_poll(multi, nullptr, 0, sliceMs, nullptr) != CURLM_OK) + { + break; + } + } + + curl_multi_remove_handle(multi, curl); + curl_multi_cleanup(multi); + return result; +#else + return curl_easy_perform(curl); +#endif + } + /** * Install the libcurl progress callback used to abort a transfer. * diff --git a/tests/unittests/CMakeLists.txt b/tests/unittests/CMakeLists.txt index ff682427b..d2c6c6c96 100644 --- a/tests/unittests/CMakeLists.txt +++ b/tests/unittests/CMakeLists.txt @@ -149,6 +149,10 @@ target_link_libraries(UnitTests PRIVATE ZLIB::ZLIB gtest gmock) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + # HttpClientCurlTests interposes getaddrinfo() and forwards via dlsym(). + target_link_libraries(UnitTests PRIVATE ${CMAKE_DL_LIBS}) +endif() if(NOT MATSDK_SQLITE_PROVIDER_RESOLVED STREQUAL "NONE") target_link_libraries(UnitTests PRIVATE SQLite3::SQLite3) endif() diff --git a/tests/unittests/HttpClientCurlTests.cpp b/tests/unittests/HttpClientCurlTests.cpp index 1d6236e19..4b964b7bc 100644 --- a/tests/unittests/HttpClientCurlTests.cpp +++ b/tests/unittests/HttpClientCurlTests.cpp @@ -31,6 +31,8 @@ #include #include +#include +#include #include #include #include @@ -1239,4 +1241,116 @@ TEST_F(HttpClientCurlLifetimeTests, OverlappingClientsWithActiveRequestsDestroyI } } +#if defined(__linux__) + +// An unreachable DNS server keeps getaddrinfo() blocked for the system resolver +// timeout. Interpose it for one reserved host so the stall is deterministic and +// needs no network; every other lookup goes to the real resolver. +namespace +{ +constexpr char kStalledHost[] = "dns-stall.invalid"; + +// Each test run is one generation, so a resolver thread detached by an earlier +// run (for example under --gtest_repeat) keeps waiting on its own release. +struct DnsStall +{ + std::mutex mutex; + std::condition_variable cv; + uint64_t generation {0}; + uint64_t entered {0}; + uint64_t released {0}; +}; + +DnsStall& GetDnsStall() +{ + static DnsStall* stall = new DnsStall(); // Leaked: a detached resolver may still use it at exit. + return *stall; +} + +uint64_t BeginDnsStall() +{ + DnsStall& stall = GetDnsStall(); + std::lock_guard lock(stall.mutex); + return ++stall.generation; +} + +void ReleaseDnsStall(uint64_t generation) +{ + DnsStall& stall = GetDnsStall(); + { + std::lock_guard lock(stall.mutex); + stall.released = generation; + } + stall.cv.notify_all(); +} +} // namespace + +extern "C" int getaddrinfo(const char* node, const char* service, const struct addrinfo* hints, + struct addrinfo** res) +{ + if (node != nullptr && std::strcmp(node, kStalledHost) == 0) + { + DnsStall& stall = GetDnsStall(); + std::unique_lock lock(stall.mutex); + const uint64_t generation = stall.generation; + stall.entered = generation; + stall.cv.notify_all(); + stall.cv.wait_for(lock, std::chrono::seconds(60), [&]() { return stall.released >= generation; }); + return EAI_AGAIN; + } + using GetAddrInfoFn = int (*)(const char*, const char*, const struct addrinfo*, struct addrinfo**); + static const auto real = reinterpret_cast(dlsym(RTLD_NEXT, "getaddrinfo")); + return (real != nullptr) ? real(node, service, hints, res) : EAI_SYSTEM; +} + +// Destroying the client while name resolution is stalled must abort and drain +// promptly: neither the abort nor curl_easy_cleanup() may wait for the resolver. +TEST(HttpClientCurlDnsStallTests, DestroyingClientDuringStalledResolutionDoesNotHang) +{ + const curl_version_info_data* versionInfo = curl_version_info(CURLVERSION_NOW); + if (!UsesPrereqCallback() || versionInfo == nullptr || versionInfo->version_num < 0x075700) + { + GTEST_SKIP() << "runtime libcurl predates CURLOPT_QUICK_EXIT (7.87.0)"; + } + if ((versionInfo->features & CURL_VERSION_ASYNCHDNS) == 0) + { + // A synchronous resolver blocks the worker itself; nothing can abort it. + GTEST_SKIP() << "runtime libcurl resolves names synchronously"; + } + + const uint64_t generation = BeginDnsStall(); + RecordingCallback callback; + std::unique_ptr client(new HttpClient_Curl()); + std::unique_ptr request(client->CreateRequest()); + request->SetUrl(std::string("http://") + kStalledHost + "/stall"); + client->SendRequestAsync(request.get(), &callback); + + bool entered = false; + { + DnsStall& stall = GetDnsStall(); + std::unique_lock lock(stall.mutex); + entered = stall.cv.wait_for(lock, std::chrono::seconds(10), [&]() { return stall.entered == generation; }); + } + if (!entered) + { + client.reset(); + ReleaseDnsStall(generation); + GTEST_SKIP() << "libcurl does not resolve through getaddrinfo() (for example, c-ares)"; + } + + const auto start = std::chrono::steady_clock::now(); + client.reset(); + const auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); + ReleaseDnsStall(generation); + + // The connect timeout is 5s; finishing well inside it proves the abort did + // not wait for it, and no resolver join extended it to the 60s stall. + EXPECT_LT(elapsed.count(), 3000) << "client teardown waited on the stalled resolver"; + EXPECT_EQ(callback.responses(), 1u); + EXPECT_EQ(callback.responsesWithResult(HttpResult_Aborted), 1u); +} + +#endif // __linux__ + #endif // MATSDK_PAL_CPP11 && !_MSC_VER && HAVE_MAT_DEFAULT_HTTP_CLIENT From d71a6072e4bdb6a6af23f2064f75c52a533d1583 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Thu, 19 Nov 2026 11:49:17 -0600 Subject: [PATCH 2/7] Keep CI checks reliable on newer runner images Include the integer type dependency in ICdsFactory.hpp and avoid the racy mkdir implementation in build-runner-tests.py. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ea7f5226-1c17-476f-abaa-90cfa4b32e3c --- lib/include/public/ICdsFactory.hpp | 1 + tests/build-runner-tests.py | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/include/public/ICdsFactory.hpp b/lib/include/public/ICdsFactory.hpp index 312c3b210..f5906969e 100644 --- a/lib/include/public/ICdsFactory.hpp +++ b/lib/include/public/ICdsFactory.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include diff --git a/tests/build-runner-tests.py b/tests/build-runner-tests.py index 8360c1142..7a64c8e04 100644 --- a/tests/build-runner-tests.py +++ b/tests/build-runner-tests.py @@ -33,7 +33,7 @@ def setUp(self): self.write_script( "out/tests/functests/FuncTests", 'printf "concurrent %s\\n" "$*" >> "$CALLS"\n' - 'if mkdir "$CASE_ROOT/first-child" 2>/dev/null; then\n' + 'if (set -C; : > "$CASE_ROOT/first-child") 2>/dev/null; then\n' ' sleep 0.05\n' ' echo first-finished >> "$CALLS"\n' ' exit "${FIRST_RESULT:-0}"\n' @@ -123,6 +123,13 @@ def test_second_child_failure_is_not_lost(self): self.assertIn("first-finished", calls) self.assertIn("second-finished", calls) + def test_child_selection_does_not_depend_on_mkdir(self): + self.write_script("bin/mkdir", "exit 0\n") + result, calls = self.run_runner(SECOND_RESULT="26") + self.assertEqual(result.returncode, 26, result.stdout + result.stderr) + self.assertIn("first-finished", calls) + self.assertIn("second-finished", calls) + if __name__ == "__main__": unittest.main() From f36e34d0d83a68797954367fd419e4c4c3f4146c Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 08:47:06 -0600 Subject: [PATCH 3/7] Pin libcurl's module after abandoning a stalled resolver CURLOPT_QUICK_EXIT lets teardown skip joining a resolver thread blocked in getaddrinfo(). That thread later returns into libcurl, so unloading the module that holds libcurl first (a shared libcurl losing its last reference, or a library that links it statically) would crash. When an aborted or timed-out transfer never finished name resolution, pin libcurl's module once with dlopen(RTLD_NOLOAD | RTLD_NODELETE). Hosts that never stall can still unload the module; the rare stalled case leaks the mapping instead of crashing. The DNS-stall test now checks the pin. Files changed: - lib/http/HttpClient_Curl.hpp - tests/unittests/HttpClientCurlTests.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 75770221-1676-4767-bba3-18994bc39f5f --- lib/http/HttpClient_Curl.hpp | 67 ++++++++++++++++++++++++- tests/unittests/HttpClientCurlTests.cpp | 11 ++++ 2 files changed, 76 insertions(+), 2 deletions(-) diff --git a/lib/http/HttpClient_Curl.hpp b/lib/http/HttpClient_Curl.hpp index c5d6bf7b6..cde931cd0 100644 --- a/lib/http/HttpClient_Curl.hpp +++ b/lib/http/HttpClient_Curl.hpp @@ -33,6 +33,7 @@ #include #include +#include #include #include "IHttpClient.hpp" @@ -90,6 +91,49 @@ inline CURLcode EnsureCurlGlobalInit() noexcept return initResult; } +struct CurlModulePinState +{ + std::once_flag once; + std::atomic pinned { false }; +}; + +inline CurlModulePinState& GetCurlModulePinState() noexcept +{ + static CurlModulePinState state; + return state; +} + +/** + * Keep the module that contains libcurl mapped for the rest of the process. + * + * CURLOPT_QUICK_EXIT lets teardown abandon a resolver thread that is still + * blocked in getaddrinfo(). That thread later returns into libcurl's code, so + * unloading the module first (a shared libcurl losing its last reference, or a + * library that links libcurl statically) would crash. Pinning happens once, + * only after such an abandonment, so hosts that never stall can still unload + * the module. Best effort: a module that cannot be pinned (for example the + * main executable, which is never unloaded) is left as is. + */ +inline bool PinCurlModuleForAbandonedResolver() noexcept +{ + CurlModulePinState& state = GetCurlModulePinState(); +#if defined(RTLD_NOLOAD) && defined(RTLD_NODELETE) + std::call_once(state.once, [&state]() { + Dl_info info {}; + if (dladdr(reinterpret_cast(&curl_easy_init), &info) == 0 || info.dli_fname == nullptr) + { + return; + } + // The handle is deliberately never closed; RTLD_NODELETE pins the module. + if (dlopen(info.dli_fname, RTLD_LAZY | RTLD_NOLOAD | RTLD_NODELETE) != nullptr) + { + state.pinned.store(true, std::memory_order_release); + } + }); +#endif + return state.pinned.load(std::memory_order_acquire); +} + // Private per-client shared state. Defined in HttpClient_Curl.cpp: it owns the // operation registry, the drain bookkeeping and the SSL settings, and it // outlives the facade because every completion captures it by shared_ptr. @@ -353,8 +397,8 @@ class CurlHttpOperation { // joins a resolver thread that can stay blocked in getaddrinfo() for the // system DNS timeout when the collector is unreachable, stalling host // process exit. Best effort: an older runtime libcurl rejects it. - // Trade-off: a resolver thread abandoned this way runs until - // getaddrinfo() returns, and must not outlive an unloaded libcurl. + // A resolver thread abandoned this way runs until getaddrinfo() + // returns; PerformAbortable() pins libcurl's module when that happens. (void)curl_easy_setopt(curl, MATSDK_CURLOPT_QUICK_EXIT, 1L); // Headers are copied into m_headersChunk during construction and the @@ -982,6 +1026,21 @@ class CurlHttpOperation { } } + /** + * Whether teardown may leave a resolver thread blocked in getaddrinfo(): + * the transfer was cut short before name resolution finished. + */ + bool ResolverMayBeAbandoned(CURLcode result) const noexcept + { + if (result != CURLE_ABORTED_BY_CALLBACK && result != CURLE_OPERATION_TIMEDOUT) + { + return false; + } + double nameLookupSeconds = 0.0; + return curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &nameLookupSeconds) != CURLE_OK || + nameLookupSeconds <= 0.0; + } + /** * Run the transfer on a private multi handle so cancellation is observed * within one poll slice. curl_easy_perform() does not invoke the progress @@ -1037,6 +1096,10 @@ class CurlHttpOperation { } } + if (ResolverMayBeAbandoned(result) && !PinCurlModuleForAbandonedResolver()) + { + LOG_WARN("Could not pin libcurl's module; it must not be unloaded while a DNS lookup is pending"); + } curl_multi_remove_handle(multi, curl); curl_multi_cleanup(multi); return result; diff --git a/tests/unittests/HttpClientCurlTests.cpp b/tests/unittests/HttpClientCurlTests.cpp index 4b964b7bc..5fc2d5831 100644 --- a/tests/unittests/HttpClientCurlTests.cpp +++ b/tests/unittests/HttpClientCurlTests.cpp @@ -1349,6 +1349,17 @@ TEST(HttpClientCurlDnsStallTests, DestroyingClientDuringStalledResolutionDoesNot EXPECT_LT(elapsed.count(), 3000) << "client teardown waited on the stalled resolver"; EXPECT_EQ(callback.responses(), 1u); EXPECT_EQ(callback.responsesWithResult(HttpResult_Aborted), 1u); + + // The abandoned resolver returns into libcurl, so its module must stay + // mapped. A libcurl inside the test executable is never unloaded anyway. + Dl_info curlModule {}; + Dl_info testModule {}; + ASSERT_NE(dladdr(reinterpret_cast(&curl_easy_init), &curlModule), 0); + ASSERT_NE(dladdr(reinterpret_cast(&GetDnsStall), &testModule), 0); + if (curlModule.dli_fbase != testModule.dli_fbase) + { + EXPECT_TRUE(GetCurlModulePinState().pinned.load()) << curlModule.dli_fname << " was not pinned"; + } } #endif // __linux__ From 89b3cb13cdf6848e84d43c31390efa085ccb4ff0 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 16:19:21 -0600 Subject: [PATCH 4/7] Fix curl teardown quick-exit lifetime safety r4811531007: pin before worker startup to avoid loader-lock deadlocks during teardown. Verified at lib/http/HttpClient_Curl.hpp:119,378. r4811531023: detect runtime support independently of header version and protect legacy easy transfers. Verified at lib/http/HttpClient_Curl.hpp:365-389. r4811531035: gate multi quick-exit on established module lifetime protection, including successful cleanup. Verified at lib/http/HttpClient_Curl.hpp:387,1067-1078. r4811531043: disable inherited proxies so the DNS regression test reaches its stalled hostname. Verified at tests/unittests/HttpClientCurlTests.cpp:1308-1350. Files changed: lib/http/HttpClient_Curl.hpp; tests/unittests/HttpClientCurlTests.cpp. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: b759695a-3b22-4233-8d5e-fa894dcdb031 --- lib/http/HttpClient_Curl.hpp | 90 ++++++++++++++----------- tests/unittests/HttpClientCurlTests.cpp | 26 ++++++- 2 files changed, 76 insertions(+), 40 deletions(-) diff --git a/lib/http/HttpClient_Curl.hpp b/lib/http/HttpClient_Curl.hpp index cde931cd0..b46544bdc 100644 --- a/lib/http/HttpClient_Curl.hpp +++ b/lib/http/HttpClient_Curl.hpp @@ -34,6 +34,7 @@ #include #include +#include #include #include "IHttpClient.hpp" @@ -104,17 +105,18 @@ inline CurlModulePinState& GetCurlModulePinState() noexcept } /** - * Keep the module that contains libcurl mapped for the rest of the process. + * Keep the module that contains libcurl mapped for the rest of the process + * before enabling quick-exit cleanup. * - * CURLOPT_QUICK_EXIT lets teardown abandon a resolver thread that is still - * blocked in getaddrinfo(). That thread later returns into libcurl's code, so + * Quick-exit cleanup can leave resolver workers running after both failed and + * successful transfers. Those workers later return into libcurl's code, so * unloading the module first (a shared libcurl losing its last reference, or a - * library that links libcurl statically) would crash. Pinning happens once, - * only after such an abandonment, so hosts that never stall can still unload - * the module. Best effort: a module that cannot be pinned (for example the - * main executable, which is never unloaded) is left as is. + * library that links libcurl statically) would crash. Pinning must happen + * before any worker starts, not from a worker that teardown may be joining. + * The main executable is already process-lifetime. For another module, if + * pinning fails, quick-exit cleanup stays disabled. */ -inline bool PinCurlModuleForAbandonedResolver() noexcept +inline bool PinCurlModuleForQuickExit() noexcept { CurlModulePinState& state = GetCurlModulePinState(); #if defined(RTLD_NOLOAD) && defined(RTLD_NODELETE) @@ -124,6 +126,16 @@ inline bool PinCurlModuleForAbandonedResolver() noexcept { return; } + struct stat moduleInfo {}; + struct stat executableInfo {}; + if (stat(info.dli_fname, &moduleInfo) == 0 && + stat("/proc/self/exe", &executableInfo) == 0 && + moduleInfo.st_dev == executableInfo.st_dev && + moduleInfo.st_ino == executableInfo.st_ino) + { + state.pinned.store(true, std::memory_order_release); + return; + } // The handle is deliberately never closed; RTLD_NODELETE pins the module. if (dlopen(info.dli_fname, RTLD_LAZY | RTLD_NOLOAD | RTLD_NODELETE) != nullptr) { @@ -349,7 +361,6 @@ class CurlHttpOperation { return; } -#if LIBCURL_VERSION_NUM >= 0x075000 const curl_version_info_data* versionInfo = curl_version_info(CURLVERSION_NOW); if (versionInfo == nullptr) { @@ -359,8 +370,27 @@ class CurlHttpOperation { EmitCreationEvent(OnCreateFailed); return; } +#if LIBCURL_VERSION_NUM >= 0x075000 m_usePrereqCallback = versionInfo->version_num >= 0x075000; #endif + if (versionInfo->version_num >= 0x075700) + { + if (PinCurlModuleForQuickExit()) + { + const CURLcode quickExitResult = curl_easy_setopt(curl, MATSDK_CURLOPT_QUICK_EXIT, 1L); + const bool useQuickExit = quickExitResult == CURLE_OK; + if (!useQuickExit) + { + LOG_WARN("curl_easy_setopt(CURLOPT_QUICK_EXIT) failed: %s", + curl_easy_strerror(quickExitResult)); + } + m_useMultiQuickExit = useQuickExit && versionInfo->version_num >= 0x081400; + } + else + { + LOG_WARN("Quick-exit cleanup disabled because libcurl's module could not be pinned"); + } + } if (!SetOption(CURLOPT_VERBOSE, 0L) || !SetOption(CURLOPT_URL, m_url.c_str()) || @@ -393,14 +423,6 @@ class CurlHttpOperation { // With NOSIGNAL, a synchronous resolver may still prevent libcurl from // enforcing a strict deadline until the resolver call returns. - // Teardown drains every operation, and curl_easy_cleanup() otherwise - // joins a resolver thread that can stay blocked in getaddrinfo() for the - // system DNS timeout when the collector is unreachable, stalling host - // process exit. Best effort: an older runtime libcurl rejects it. - // A resolver thread abandoned this way runs until getaddrinfo() - // returns; PerformAbortable() pins libcurl's module when that happens. - (void)curl_easy_setopt(curl, MATSDK_CURLOPT_QUICK_EXIT, 1L); - // Headers are copied into m_headersChunk during construction and the // curl_slist is kept alive until destruction, so the original map does // not need operation-lifetime storage. @@ -868,6 +890,7 @@ class CurlHttpOperation { curl_socket_t sockextr = CURL_SOCKET_BAD; bool m_usePrereqCallback{false}; // Chosen once from the loaded libcurl version. + bool m_useMultiQuickExit{false}; // Available since libcurl 8.20.0. bool m_connectionReady{false}; // Only accessed by the transfer's worker thread. curl_off_t nread = 0; @@ -1026,21 +1049,6 @@ class CurlHttpOperation { } } - /** - * Whether teardown may leave a resolver thread blocked in getaddrinfo(): - * the transfer was cut short before name resolution finished. - */ - bool ResolverMayBeAbandoned(CURLcode result) const noexcept - { - if (result != CURLE_ABORTED_BY_CALLBACK && result != CURLE_OPERATION_TIMEDOUT) - { - return false; - } - double nameLookupSeconds = 0.0; - return curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &nameLookupSeconds) != CURLE_OK || - nameLookupSeconds <= 0.0; - } - /** * Run the transfer on a private multi handle so cancellation is observed * within one poll slice. curl_easy_perform() does not invoke the progress @@ -1055,9 +1063,17 @@ class CurlHttpOperation { { return CURLE_OUT_OF_MEMORY; } - // From libcurl 8.20.0 resolver threads belong to the multi handle; do - // not join them. - (void)curl_multi_setopt(multi, MATSDK_CURLMOPT_QUICK_EXIT, 1L); + // From libcurl 8.20.0 resolver threads belong to the multi handle; only + // detach them after the module was pinned during operation creation. + if (m_useMultiQuickExit) + { + const CURLMcode quickExitResult = curl_multi_setopt(multi, MATSDK_CURLMOPT_QUICK_EXIT, 1L); + if (quickExitResult != CURLM_OK) + { + LOG_WARN("curl_multi_setopt(CURLMOPT_QUICK_EXIT) failed: %s", + curl_multi_strerror(quickExitResult)); + } + } if (curl_multi_add_handle(multi, curl) != CURLM_OK) { curl_multi_cleanup(multi); @@ -1096,10 +1112,6 @@ class CurlHttpOperation { } } - if (ResolverMayBeAbandoned(result) && !PinCurlModuleForAbandonedResolver()) - { - LOG_WARN("Could not pin libcurl's module; it must not be unloaded while a DNS lookup is pending"); - } curl_multi_remove_handle(multi, curl); curl_multi_cleanup(multi); return result; diff --git a/tests/unittests/HttpClientCurlTests.cpp b/tests/unittests/HttpClientCurlTests.cpp index 5fc2d5831..f9b40a5f7 100644 --- a/tests/unittests/HttpClientCurlTests.cpp +++ b/tests/unittests/HttpClientCurlTests.cpp @@ -1305,6 +1305,29 @@ extern "C" int getaddrinfo(const char* node, const char* service, const struct a // Destroying the client while name resolution is stalled must abort and drain // promptly: neither the abort nor curl_easy_cleanup() may wait for the resolver. +class NoProxyRecordingCallback : public RecordingCallback +{ +public: + CURLcode noProxyResult() const + { + return m_noProxyResult; + } + + void OnHttpStateEvent(HttpStateEvent state, void* handle, size_t size) override + { + if (state == OnCreated) + { + m_noProxyResult = handle == nullptr + ? CURLE_FAILED_INIT + : curl_easy_setopt(static_cast(handle), CURLOPT_NOPROXY, "*"); + } + RecordingCallback::OnHttpStateEvent(state, handle, size); + } + +private: + CURLcode m_noProxyResult {CURLE_FAILED_INIT}; +}; + TEST(HttpClientCurlDnsStallTests, DestroyingClientDuringStalledResolutionDoesNotHang) { const curl_version_info_data* versionInfo = curl_version_info(CURLVERSION_NOW); @@ -1319,11 +1342,12 @@ TEST(HttpClientCurlDnsStallTests, DestroyingClientDuringStalledResolutionDoesNot } const uint64_t generation = BeginDnsStall(); - RecordingCallback callback; + NoProxyRecordingCallback callback; std::unique_ptr client(new HttpClient_Curl()); std::unique_ptr request(client->CreateRequest()); request->SetUrl(std::string("http://") + kStalledHost + "/stall"); client->SendRequestAsync(request.get(), &callback); + ASSERT_EQ(callback.noProxyResult(), CURLE_OK); bool entered = false; { From 42f4facb70911742e6a922fe313756b634f83545 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 16:47:11 -0600 Subject: [PATCH 5/7] curl: harden module pinning and cover dlclose 4813699957: identify the main executable by its loaded mapping instead of a current-directory-sensitive path, with a chdir regression. 4813699987: add isolated fetched-curl unload regressions for stalled resolver release after dlclose and idle workers after a successful transfer. Files changed: lib/http/HttpClient_Curl.hpp; tests/unittests/CMakeLists.txt; tests/unittests/HttpClientCurlTests.cpp; tests/unittests/curl-module-unload-module.cpp; tests/unittests/curl-module-unload-test-api.hpp; tests/unittests/curl-module-unload-test.cpp. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: b759695a-3b22-4233-8d5e-fa894dcdb031 --- lib/http/HttpClient_Curl.hpp | 35 +- tests/unittests/CMakeLists.txt | 26 ++ tests/unittests/HttpClientCurlTests.cpp | 49 +++ tests/unittests/curl-module-unload-module.cpp | 89 +++++ .../unittests/curl-module-unload-test-api.hpp | 14 + tests/unittests/curl-module-unload-test.cpp | 325 ++++++++++++++++++ 6 files changed, 531 insertions(+), 7 deletions(-) create mode 100644 tests/unittests/curl-module-unload-module.cpp create mode 100644 tests/unittests/curl-module-unload-test-api.hpp create mode 100644 tests/unittests/curl-module-unload-test.cpp diff --git a/lib/http/HttpClient_Curl.hpp b/lib/http/HttpClient_Curl.hpp index b46544bdc..c6b426963 100644 --- a/lib/http/HttpClient_Curl.hpp +++ b/lib/http/HttpClient_Curl.hpp @@ -34,7 +34,9 @@ #include #include -#include +#if defined(__GLIBC__) +#include +#endif #include #include "IHttpClient.hpp" @@ -104,6 +106,28 @@ inline CurlModulePinState& GetCurlModulePinState() noexcept return state; } +#if defined(__GLIBC__) +inline bool CurlModuleIsMainExecutable(void* moduleBase) noexcept +{ + void* mainHandle = dlopen(nullptr, RTLD_LAZY); + if (mainHandle == nullptr) + { + return false; + } + + link_map* mainModule = nullptr; + Dl_info mainInfo {}; + const bool isMainExecutable = + dlinfo(mainHandle, RTLD_DI_LINKMAP, &mainModule) == 0 && + mainModule != nullptr && + mainModule->l_ld != nullptr && + dladdr(reinterpret_cast(mainModule->l_ld), &mainInfo) != 0 && + mainInfo.dli_fbase == moduleBase; + dlclose(mainHandle); + return isMainExecutable; +} +#endif + /** * Keep the module that contains libcurl mapped for the rest of the process * before enabling quick-exit cleanup. @@ -126,16 +150,13 @@ inline bool PinCurlModuleForQuickExit() noexcept { return; } - struct stat moduleInfo {}; - struct stat executableInfo {}; - if (stat(info.dli_fname, &moduleInfo) == 0 && - stat("/proc/self/exe", &executableInfo) == 0 && - moduleInfo.st_dev == executableInfo.st_dev && - moduleInfo.st_ino == executableInfo.st_ino) +#if defined(__GLIBC__) + if (CurlModuleIsMainExecutable(info.dli_fbase)) { state.pinned.store(true, std::memory_order_release); return; } +#endif // The handle is deliberately never closed; RTLD_NODELETE pins the module. if (dlopen(info.dli_fname, RTLD_LAZY | RTLD_NOLOAD | RTLD_NODELETE) != nullptr) { diff --git a/tests/unittests/CMakeLists.txt b/tests/unittests/CMakeLists.txt index d2c6c6c96..349c84e74 100644 --- a/tests/unittests/CMakeLists.txt +++ b/tests/unittests/CMakeLists.txt @@ -163,3 +163,29 @@ endif() add_test(NAME UnitTests COMMAND UnitTests "--gtest_output=xml:${PROJECT_BINARY_DIR}/test-reports/UnitTests.xml") set_tests_properties(UnitTests PROPERTIES WORKING_DIRECTORY "${PROJECT_BINARY_DIR}") + +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND MATSDK_CURL_PROVIDER_UPPER STREQUAL "FETCH") + find_package(Threads REQUIRED) + + add_library(CurlModuleUnloadModule MODULE + curl-module-unload-module.cpp + ) + target_include_directories(CurlModuleUnloadModule PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}") + target_link_libraries(CurlModuleUnloadModule PRIVATE matsdk_test_config mat) + set_target_properties(CurlModuleUnloadModule PROPERTIES PREFIX "") + + add_executable(CurlModuleUnloadTest + curl-module-unload-test.cpp + ) + target_include_directories(CurlModuleUnloadTest PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}") + target_link_libraries(CurlModuleUnloadTest PRIVATE matsdk_test_config Threads::Threads ${CMAKE_DL_LIBS}) + set_target_properties(CurlModuleUnloadTest PROPERTIES ENABLE_EXPORTS ON) + + add_dependencies(UnitTests CurlModuleUnloadModule CurlModuleUnloadTest) + add_test(NAME CurlModuleUnloadStalledDns + COMMAND CurlModuleUnloadTest $ stalled-dns) + add_test(NAME CurlModuleUnloadAfterSuccessfulTransfer + COMMAND CurlModuleUnloadTest $ successful-transfer) + set_tests_properties(CurlModuleUnloadStalledDns CurlModuleUnloadAfterSuccessfulTransfer + PROPERTIES TIMEOUT 20) +endif() diff --git a/tests/unittests/HttpClientCurlTests.cpp b/tests/unittests/HttpClientCurlTests.cpp index f9b40a5f7..501d38cb6 100644 --- a/tests/unittests/HttpClientCurlTests.cpp +++ b/tests/unittests/HttpClientCurlTests.cpp @@ -1305,6 +1305,55 @@ extern "C" int getaddrinfo(const char* node, const char* service, const struct a // Destroying the client while name resolution is stalled must abort and drain // promptly: neither the abort nor curl_easy_cleanup() may wait for the resolver. +#if defined(__GLIBC__) +namespace +{ +void CurlModuleMainImageAnchor() +{ +} + +class CurrentDirectoryGuard +{ +public: + CurrentDirectoryGuard() + { + char path[4096]; + if (getcwd(path, sizeof(path)) != nullptr) + { + m_path = path; + } + } + + ~CurrentDirectoryGuard() + { + if (!m_path.empty()) + { + chdir(m_path.c_str()); + } + } + + bool valid() const + { + return !m_path.empty(); + } + +private: + std::string m_path; +}; +} // namespace + +TEST(HttpClientCurlModuleTests, IdentifiesMainExecutableAfterWorkingDirectoryChanges) +{ + CurrentDirectoryGuard currentDirectory; + ASSERT_TRUE(currentDirectory.valid()); + ASSERT_EQ(chdir("/"), 0); + + Dl_info mainInfo {}; + ASSERT_NE(dladdr(reinterpret_cast(&CurlModuleMainImageAnchor), &mainInfo), 0); + EXPECT_TRUE(CurlModuleIsMainExecutable(mainInfo.dli_fbase)); +} +#endif + class NoProxyRecordingCallback : public RecordingCallback { public: diff --git a/tests/unittests/curl-module-unload-module.cpp b/tests/unittests/curl-module-unload-module.cpp new file mode 100644 index 000000000..3fb4944d0 --- /dev/null +++ b/tests/unittests/curl-module-unload-module.cpp @@ -0,0 +1,89 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +#include "mat/config.h" +#include "http/HttpClient_Curl.hpp" +#include "curl-module-unload-test-api.hpp" + +#include +#include + +namespace +{ +class ResponseCallback : public MAT::IHttpResponseCallback +{ +public: + void OnHttpResponse(MAT::IHttpResponse* response) override + { + const int result = static_cast(response->GetResult()); + delete response; + + if (g_gate != nullptr) + { + pthread_mutex_lock(&g_gate->mutex); + g_gate->responseResult = result; + g_gate->responseReceived = true; + pthread_cond_broadcast(&g_gate->condition); + pthread_mutex_unlock(&g_gate->mutex); + } + } + + static CurlModuleUnloadGate* g_gate; +}; + +CurlModuleUnloadGate* ResponseCallback::g_gate = nullptr; +ResponseCallback g_callback; +std::unique_ptr g_client; +std::unique_ptr g_request; + +bool StartRequest(CurlModuleUnloadGate* gate, const std::string& url) +{ + if (gate == nullptr || g_client != nullptr) + { + return false; + } + + ResponseCallback::g_gate = gate; + g_client.reset(new MAT::HttpClient_Curl()); + g_request.reset(g_client->CreateRequest()); + g_request->SetUrl(url); + g_client->SendRequestAsync(g_request.get(), &g_callback); + return true; +} +} // namespace + +extern "C" __attribute__((visibility("default"))) bool StartStalledRequest(CurlModuleUnloadGate* gate) +{ + return StartRequest(gate, "http://dns-stall.invalid/"); +} + +extern "C" __attribute__((visibility("default"))) bool StartSuccessfulRequest( + CurlModuleUnloadGate* gate, const char* url) +{ + return url != nullptr && StartRequest(gate, url); +} + +extern "C" __attribute__((visibility("default"))) void DestroyClient() +{ + g_client.reset(); + g_request.reset(); +} + +extern "C" __attribute__((visibility("default"))) bool WasResponseSuccessful() +{ + if (ResponseCallback::g_gate == nullptr) + { + return false; + } + pthread_mutex_lock(&ResponseCallback::g_gate->mutex); + const bool success = ResponseCallback::g_gate->responseReceived && + ResponseCallback::g_gate->responseResult == static_cast(MAT::HttpResult_OK); + pthread_mutex_unlock(&ResponseCallback::g_gate->mutex); + return success; +} + +extern "C" __attribute__((visibility("default"))) void* GetCurlFunctionAddress() +{ + return reinterpret_cast(&curl_easy_init); +} diff --git a/tests/unittests/curl-module-unload-test-api.hpp b/tests/unittests/curl-module-unload-test-api.hpp new file mode 100644 index 000000000..2b2371be0 --- /dev/null +++ b/tests/unittests/curl-module-unload-test-api.hpp @@ -0,0 +1,14 @@ +#pragma once + +#include + +struct CurlModuleUnloadGate +{ + pthread_mutex_t mutex; + pthread_cond_t condition; + bool resolverEntered {false}; + bool resolverReleased {false}; + bool resolverReturned {false}; + bool responseReceived {false}; + int responseResult {-1}; +}; diff --git a/tests/unittests/curl-module-unload-test.cpp b/tests/unittests/curl-module-unload-test.cpp new file mode 100644 index 000000000..0a5b5bea0 --- /dev/null +++ b/tests/unittests/curl-module-unload-test.cpp @@ -0,0 +1,325 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +#include "curl-module-unload-test-api.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace +{ +CurlModuleUnloadGate* g_gate = nullptr; + +using StartStalledRequestFn = bool (*)(CurlModuleUnloadGate*); +using StartSuccessfulRequestFn = bool (*)(CurlModuleUnloadGate*, const char*); +using DestroyClientFn = void (*)(); +using WasResponseSuccessfulFn = bool (*)(); +using GetCurlFunctionAddressFn = void* (*)(); + +enum class GateFlag +{ + ResolverEntered, + ResolverReturned, + ResponseReceived +}; + +bool IsSet(const CurlModuleUnloadGate& gate, GateFlag flag) +{ + switch (flag) + { + case GateFlag::ResolverEntered: + return gate.resolverEntered; + case GateFlag::ResolverReturned: + return gate.resolverReturned; + case GateFlag::ResponseReceived: + return gate.responseReceived; + } + return false; +} + +bool WaitForFlag(CurlModuleUnloadGate& gate, GateFlag flag, int timeoutSeconds) +{ + timespec deadline {}; + if (clock_gettime(CLOCK_REALTIME, &deadline) != 0) + { + return false; + } + deadline.tv_sec += timeoutSeconds; + + pthread_mutex_lock(&gate.mutex); + int result = 0; + while (!IsSet(gate, flag) && result == 0) + { + result = pthread_cond_timedwait(&gate.condition, &gate.mutex, &deadline); + } + const bool ready = IsSet(gate, flag); + pthread_mutex_unlock(&gate.mutex); + return ready; +} + +class LocalHttpServer +{ +public: + bool Start() + { + m_socket = socket(AF_INET, SOCK_STREAM, 0); + if (m_socket < 0) + { + return false; + } + + int reuseAddress = 1; + setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuseAddress, sizeof(reuseAddress)); + sockaddr_in address {}; + address.sin_family = AF_INET; + address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + address.sin_port = 0; + if (bind(m_socket, reinterpret_cast(&address), sizeof(address)) != 0 || + listen(m_socket, 1) != 0) + { + close(m_socket); + m_socket = -1; + return false; + } + + socklen_t addressSize = sizeof(address); + if (getsockname(m_socket, reinterpret_cast(&address), &addressSize) != 0) + { + close(m_socket); + m_socket = -1; + return false; + } + m_port = ntohs(address.sin_port); + m_worker = std::thread([this]() { ServeOneRequest(); }); + return true; + } + + ~LocalHttpServer() + { + if (m_socket >= 0) + { + shutdown(m_socket, SHUT_RDWR); + close(m_socket); + } + if (m_worker.joinable()) + { + m_worker.join(); + } + } + + std::string Url() const + { + return "http://localhost:" + std::to_string(m_port) + "/"; + } + +private: + void ServeOneRequest() + { + const int client = accept(m_socket, nullptr, nullptr); + if (client < 0) + { + return; + } + + char request[2048]; + recv(client, request, sizeof(request), 0); + static const char response[] = + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; + send(client, response, sizeof(response) - 1, MSG_NOSIGNAL); + close(client); + } + + int m_socket {-1}; + uint16_t m_port {0}; + std::thread m_worker; +}; + +template +T LoadFunction(void* module, const char* name) +{ + dlerror(); + void* symbol = dlsym(module, name); + if (dlerror() != nullptr) + { + return nullptr; + } + return reinterpret_cast(symbol); +} +} // namespace + +extern "C" int getaddrinfo( + const char* node, const char* service, const addrinfo* hints, addrinfo** result) +{ + using GetAddrInfoFn = int (*)(const char*, const char*, const addrinfo*, addrinfo**); + static GetAddrInfoFn realGetAddrInfo = + reinterpret_cast(dlsym(RTLD_NEXT, "getaddrinfo")); + if (realGetAddrInfo == nullptr) + { + return EAI_FAIL; + } + + if (g_gate != nullptr && node != nullptr && std::strcmp(node, "dns-stall.invalid") == 0) + { + pthread_mutex_lock(&g_gate->mutex); + g_gate->resolverEntered = true; + pthread_cond_broadcast(&g_gate->condition); + while (!g_gate->resolverReleased) + { + pthread_cond_wait(&g_gate->condition, &g_gate->mutex); + } + g_gate->resolverReturned = true; + pthread_cond_broadcast(&g_gate->condition); + pthread_mutex_unlock(&g_gate->mutex); + return EAI_AGAIN; + } + + const int status = realGetAddrInfo(node, service, hints, result); + if (g_gate != nullptr && node != nullptr && std::strcmp(node, "localhost") == 0) + { + pthread_mutex_lock(&g_gate->mutex); + g_gate->resolverReturned = true; + pthread_cond_broadcast(&g_gate->condition); + pthread_mutex_unlock(&g_gate->mutex); + } + return status; +} + +int main(int argc, char** argv) +{ + if (argc != 3 || (std::strcmp(argv[2], "stalled-dns") != 0 && + std::strcmp(argv[2], "successful-transfer") != 0)) + { + std::fprintf(stderr, "usage: %s \n", argv[0]); + return 2; + } + + unsetenv("http_proxy"); + unsetenv("https_proxy"); + unsetenv("all_proxy"); + unsetenv("HTTP_PROXY"); + unsetenv("HTTPS_PROXY"); + unsetenv("ALL_PROXY"); + + CurlModuleUnloadGate gate {}; + pthread_mutex_init(&gate.mutex, nullptr); + pthread_cond_init(&gate.condition, nullptr); + g_gate = &gate; + + LocalHttpServer server; + const bool stalledDns = std::strcmp(argv[2], "stalled-dns") == 0; + if (!stalledDns && !server.Start()) + { + std::fprintf(stderr, "failed to start localhost HTTP server\n"); + return 1; + } + + void* module = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL); + if (module == nullptr) + { + std::fprintf(stderr, "dlopen failed: %s\n", dlerror()); + return 1; + } + + const auto startStalled = LoadFunction(module, "StartStalledRequest"); + const auto startSuccessful = LoadFunction(module, "StartSuccessfulRequest"); + const auto destroyClient = LoadFunction(module, "DestroyClient"); + const auto responseSucceeded = LoadFunction(module, "WasResponseSuccessful"); + const auto getCurlFunctionAddress = + LoadFunction(module, "GetCurlFunctionAddress"); + if (startStalled == nullptr || startSuccessful == nullptr || destroyClient == nullptr || + responseSucceeded == nullptr || getCurlFunctionAddress == nullptr) + { + std::fprintf(stderr, "failed to load module test functions\n"); + dlclose(module); + return 1; + } + + void* curlFunctionAddress = getCurlFunctionAddress(); + const bool started = stalledDns + ? startStalled(&gate) + : startSuccessful(&gate, server.Url().c_str()); + if (!started) + { + std::fprintf(stderr, "failed to start HTTP request\n"); + dlclose(module); + return 1; + } + + if (!WaitForFlag(gate, stalledDns ? GateFlag::ResolverEntered : GateFlag::ResponseReceived, 10)) + { + std::fprintf(stderr, "request did not reach the expected resolver/response state\n"); + destroyClient(); + dlclose(module); + return 1; + } + if (!stalledDns && !responseSucceeded()) + { + std::fprintf(stderr, "localhost request failed\n"); + destroyClient(); + dlclose(module); + return 1; + } + + const auto destroyStart = std::chrono::steady_clock::now(); + destroyClient(); + const auto destroyTime = std::chrono::steady_clock::now() - destroyStart; + if (destroyTime > std::chrono::seconds(3)) + { + std::fprintf(stderr, "client destruction blocked while resolver worker was active\n"); + dlclose(module); + return 1; + } + if (stalledDns && !WaitForFlag(gate, GateFlag::ResponseReceived, 5)) + { + std::fprintf(stderr, "stalled request callback did not complete during destruction\n"); + dlclose(module); + return 1; + } + + if (dlclose(module) != 0) + { + std::fprintf(stderr, "dlclose failed: %s\n", dlerror()); + return 1; + } + + Dl_info curlInfo {}; + if (dladdr(curlFunctionAddress, &curlInfo) == 0 || curlInfo.dli_fbase == nullptr) + { + std::fprintf(stderr, "libcurl-containing module was unloaded after dlclose\n"); + return 1; + } + + if (stalledDns) + { + pthread_mutex_lock(&gate.mutex); + gate.resolverReleased = true; + pthread_cond_broadcast(&gate.condition); + pthread_mutex_unlock(&gate.mutex); + if (!WaitForFlag(gate, GateFlag::ResolverReturned, 5)) + { + std::fprintf(stderr, "stalled resolver did not return after release\n"); + return 1; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + if (dladdr(curlFunctionAddress, &curlInfo) == 0) + { + std::fprintf(stderr, "libcurl-containing module unloaded while resolver returned\n"); + return 1; + } + } + + std::printf("%s unload regression passed\n", argv[2]); + return 0; +} From 67e5131d769567e684e1b40e6e60a8a35fc7b76c Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 17:04:58 -0600 Subject: [PATCH 6/7] curl: preserve older runtimes and exercise resolver unload 4813831962: keep curl_multi_poll and curl_multi_wait optional at load time; use bounded multi polling when available and retain the legacy easy path otherwise. 4813831981 and 4813699987: route a reserved test hostname through the controlled resolver to loopback and require its return before teardown, ensuring the successful transfer leaves a real resolver worker idle. Files changed: lib/http/HttpClient_Curl.hpp; tests/unittests/curl-module-unload-test.cpp. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: b759695a-3b22-4233-8d5e-fa894dcdb031 --- lib/http/HttpClient_Curl.hpp | 22 ++++++++++++++++++++- tests/unittests/curl-module-unload-test.cpp | 22 ++++++++++++++------- 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/lib/http/HttpClient_Curl.hpp b/lib/http/HttpClient_Curl.hpp index c6b426963..fe712cc8c 100644 --- a/lib/http/HttpClient_Curl.hpp +++ b/lib/http/HttpClient_Curl.hpp @@ -39,6 +39,12 @@ #endif #include +#if LIBCURL_VERSION_NUM >= 0x074200 && defined(__GNUC__) +// Newer headers may be paired with an older runtime libcurl. +#pragma weak curl_multi_poll +#pragma weak curl_multi_wait +#endif + #include "IHttpClient.hpp" #include "IBoundedHttpClientCancel.hpp" #include "pal/PAL.hpp" @@ -1079,6 +1085,17 @@ class CurlHttpOperation { CURLcode PerformAbortable() { #if LIBCURL_VERSION_NUM >= 0x074200 // libcurl 7.66.0: curl_multi_poll +#if defined(__GNUC__) + const auto multiPoll = curl_multi_poll; + const auto multiWait = curl_multi_wait; + if (multiPoll == nullptr && multiWait == nullptr) + { + return curl_easy_perform(curl); + } +#else + const auto multiPoll = &curl_multi_poll; + const auto multiWait = &curl_multi_wait; +#endif CURLM* multi = curl_multi_init(); if (multi == nullptr) { @@ -1127,7 +1144,10 @@ class CurlHttpOperation { result = CURLE_ABORTED_BY_CALLBACK; break; } - if (curl_multi_poll(multi, nullptr, 0, sliceMs, nullptr) != CURLM_OK) + const CURLMcode pollResult = multiPoll != nullptr + ? multiPoll(multi, nullptr, 0, sliceMs, nullptr) + : multiWait(multi, nullptr, 0, sliceMs, nullptr); + if (pollResult != CURLM_OK) { break; } diff --git a/tests/unittests/curl-module-unload-test.cpp b/tests/unittests/curl-module-unload-test.cpp index 0a5b5bea0..7b7d187b3 100644 --- a/tests/unittests/curl-module-unload-test.cpp +++ b/tests/unittests/curl-module-unload-test.cpp @@ -119,9 +119,9 @@ class LocalHttpServer } } - std::string Url() const + std::string Url(const char* hostname) const { - return "http://localhost:" + std::to_string(m_port) + "/"; + return "http://" + std::string(hostname) + ":" + std::to_string(m_port) + "/"; } private: @@ -185,15 +185,16 @@ extern "C" int getaddrinfo( return EAI_AGAIN; } - const int status = realGetAddrInfo(node, service, hints, result); - if (g_gate != nullptr && node != nullptr && std::strcmp(node, "localhost") == 0) + if (g_gate != nullptr && node != nullptr && std::strcmp(node, "idle-worker.invalid") == 0) { + const int status = realGetAddrInfo("127.0.0.1", service, hints, result); pthread_mutex_lock(&g_gate->mutex); g_gate->resolverReturned = true; pthread_cond_broadcast(&g_gate->condition); pthread_mutex_unlock(&g_gate->mutex); + return status; } - return status; + return realGetAddrInfo(node, service, hints, result); } int main(int argc, char** argv) @@ -249,7 +250,7 @@ int main(int argc, char** argv) void* curlFunctionAddress = getCurlFunctionAddress(); const bool started = stalledDns ? startStalled(&gate) - : startSuccessful(&gate, server.Url().c_str()); + : startSuccessful(&gate, server.Url("idle-worker.invalid").c_str()); if (!started) { std::fprintf(stderr, "failed to start HTTP request\n"); @@ -266,7 +267,14 @@ int main(int argc, char** argv) } if (!stalledDns && !responseSucceeded()) { - std::fprintf(stderr, "localhost request failed\n"); + std::fprintf(stderr, "DNS-interposed request failed\n"); + destroyClient(); + dlclose(module); + return 1; + } + if (!stalledDns && !WaitForFlag(gate, GateFlag::ResolverReturned, 5)) + { + std::fprintf(stderr, "successful request did not use the test resolver\n"); destroyClient(); dlclose(module); return 1; From 4f489a35a92ac4bb42755396191c452617a08d99 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 17:20:47 -0600 Subject: [PATCH 7/7] tests: cover curl loading without optional wait symbols 4813891935: add system-libcurl shims that omit curl_multi_poll, then omit both poll and wait. The load-only host verifies the selected shim is mapped and dlopens the SDK module with RTLD_NOW, catching strong references before runtime fallback can run. Files changed: tests/unittests/CMakeLists.txt; tests/unittests/curl-optional-symbol-load-module.cpp; tests/unittests/curl-optional-symbol-load-test.cpp; tests/unittests/curl-runtime-shim.cpp. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: b759695a-3b22-4233-8d5e-fa894dcdb031 --- tests/unittests/CMakeLists.txt | 70 ++++++++++++++ .../curl-optional-symbol-load-module.cpp | 17 ++++ .../curl-optional-symbol-load-test.cpp | 92 +++++++++++++++++++ tests/unittests/curl-runtime-shim.cpp | 55 +++++++++++ 4 files changed, 234 insertions(+) create mode 100644 tests/unittests/curl-optional-symbol-load-module.cpp create mode 100644 tests/unittests/curl-optional-symbol-load-test.cpp create mode 100644 tests/unittests/curl-runtime-shim.cpp diff --git a/tests/unittests/CMakeLists.txt b/tests/unittests/CMakeLists.txt index 349c84e74..15cb34021 100644 --- a/tests/unittests/CMakeLists.txt +++ b/tests/unittests/CMakeLists.txt @@ -189,3 +189,73 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND MATSDK_CURL_PROVIDER_UPPER STREQUAL "F set_tests_properties(CurlModuleUnloadStalledDns CurlModuleUnloadAfterSuccessfulTransfer PROPERTIES TIMEOUT 20) endif() + +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND MATSDK_CURL_PROVIDER_UPPER STREQUAL "SYSTEM" + AND CURL_LIBRARY_RELEASE MATCHES "\\.so") + execute_process( + COMMAND "${CMAKE_NM}" -D --with-symbol-versions "${CURL_LIBRARY_RELEASE}" + RESULT_VARIABLE curlNmResult + OUTPUT_VARIABLE curlDynamicSymbols + ERROR_QUIET + ) + if(curlNmResult EQUAL 0) + string(REGEX MATCH "curl_easy_init@+([^ \t\r\n]+)" curlVersionedSymbol "${curlDynamicSymbols}") + set(curlSymbolVersion "${CMAKE_MATCH_1}") + endif() + + if(curlSymbolVersion) + set(curlShimVersionScript "${CMAKE_CURRENT_BINARY_DIR}/curl-runtime-shim.map") + file(WRITE "${curlShimVersionScript}" + "${curlSymbolVersion} {\n global: curl_*;\n local: *;\n};\n") + + add_library(CurlOptionalSymbolLoadModule MODULE + curl-optional-symbol-load-module.cpp + ) + target_include_directories(CurlOptionalSymbolLoadModule PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}") + target_link_libraries(CurlOptionalSymbolLoadModule PRIVATE matsdk_test_config mat) + set_target_properties(CurlOptionalSymbolLoadModule PROPERTIES PREFIX "") + + add_executable(CurlOptionalSymbolLoadTest + curl-optional-symbol-load-test.cpp + ) + target_link_libraries(CurlOptionalSymbolLoadTest PRIVATE "${CMAKE_DL_LIBS}") + + foreach(shim IN ITEMS CurlRuntimeShimMultiWait CurlRuntimeShimNoWait) + string(TOLOWER "${shim}" shimDirectoryName) + set(shimDirectory "${CMAKE_CURRENT_BINARY_DIR}/${shimDirectoryName}") + add_library(${shim} SHARED curl-runtime-shim.cpp) + target_link_options(${shim} PRIVATE "LINKER:--version-script=${curlShimVersionScript}") + set_target_properties(${shim} PROPERTIES + OUTPUT_NAME curl + SOVERSION 4 + LIBRARY_OUTPUT_DIRECTORY "${shimDirectory}" + ) + endforeach() + target_compile_definitions(CurlRuntimeShimMultiWait PRIVATE CURL_RUNTIME_SHIM_WITH_MULTI_WAIT) + + add_dependencies(UnitTests + CurlOptionalSymbolLoadModule + CurlOptionalSymbolLoadTest + CurlRuntimeShimMultiWait + CurlRuntimeShimNoWait + ) + add_test(NAME CurlOptionalSymbolLoadWithoutPoll + COMMAND CurlOptionalSymbolLoadTest + $ + $ + no-poll + ) + add_test(NAME CurlOptionalSymbolLoadWithoutPollOrWait + COMMAND CurlOptionalSymbolLoadTest + $ + $ + no-wait + ) + set_tests_properties(CurlOptionalSymbolLoadWithoutPoll + PROPERTIES ENVIRONMENT "LD_LIBRARY_PATH=${CMAKE_CURRENT_BINARY_DIR}/curlruntimeshimmultiwait") + set_tests_properties(CurlOptionalSymbolLoadWithoutPollOrWait + PROPERTIES ENVIRONMENT "LD_LIBRARY_PATH=${CMAKE_CURRENT_BINARY_DIR}/curlruntimeshimnowait") + else() + message(STATUS "Skipping optional-symbol load tests: unable to read the libcurl symbol version") + endif() +endif() diff --git a/tests/unittests/curl-optional-symbol-load-module.cpp b/tests/unittests/curl-optional-symbol-load-module.cpp new file mode 100644 index 000000000..5fd4280c6 --- /dev/null +++ b/tests/unittests/curl-optional-symbol-load-module.cpp @@ -0,0 +1,17 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +#include "mat/config.h" +#include "http/HttpClient_Curl.hpp" + +extern "C" __attribute__((visibility("default"))) MAT::HttpClient_Curl* CreateCurlHttpClient() +{ + return new MAT::HttpClient_Curl(); +} + +extern "C" __attribute__((visibility("default"))) void DestroyCurlHttpClient( + MAT::HttpClient_Curl* client) +{ + delete client; +} diff --git a/tests/unittests/curl-optional-symbol-load-test.cpp b/tests/unittests/curl-optional-symbol-load-test.cpp new file mode 100644 index 000000000..73b3c5b7b --- /dev/null +++ b/tests/unittests/curl-optional-symbol-load-test.cpp @@ -0,0 +1,92 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +#include +#include +#include +#include + +#include +#include + +namespace +{ +bool IsExpectedRuntimeLoaded(void* module, const char* expectedPath) +{ + char expected[PATH_MAX]; + if (realpath(expectedPath, expected) == nullptr) + { + return false; + } + + link_map* moduleMap = nullptr; + if (dlinfo(module, RTLD_DI_LINKMAP, &moduleMap) != 0 || moduleMap == nullptr) + { + return false; + } + + for (link_map* current = moduleMap; current != nullptr; current = current->l_next) + { + if (current->l_name == nullptr || std::strstr(current->l_name, "libcurl.so") == nullptr) + { + continue; + } + + char actual[PATH_MAX]; + if (realpath(current->l_name, actual) != nullptr && std::strcmp(expected, actual) == 0) + { + return true; + } + } + return false; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 4 || (std::strcmp(argv[3], "no-poll") != 0 && std::strcmp(argv[3], "no-wait") != 0)) + { + std::fprintf(stderr, "usage: %s \n", argv[0]); + return 2; + } + + void* module = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL); + if (module == nullptr) + { + std::fprintf(stderr, "SDK module failed to load: %s\n", dlerror()); + return 1; + } + + void* runtime = dlopen(argv[2], RTLD_NOW | RTLD_LOCAL); + if (runtime == nullptr) + { + std::fprintf(stderr, "runtime shim failed to load: %s\n", dlerror()); + dlclose(module); + return 1; + } + + if (!IsExpectedRuntimeLoaded(module, argv[2])) + { + std::fprintf(stderr, "SDK module did not load the expected curl runtime shim\n"); + dlclose(runtime); + dlclose(module); + return 1; + } + + const bool hasPoll = dlsym(runtime, "curl_multi_poll") != nullptr; + const bool hasWait = dlsym(runtime, "curl_multi_wait") != nullptr; + const bool expectedWait = std::strcmp(argv[3], "no-poll") == 0; + if (hasPoll || (hasWait != expectedWait)) + { + std::fprintf(stderr, "runtime shim exposes unexpected curl_multi_poll/curl_multi_wait symbols\n"); + dlclose(runtime); + dlclose(module); + return 1; + } + + std::printf("SDK module loaded with expected optional curl symbols absent\n"); + dlclose(runtime); + dlclose(module); + return 0; +} diff --git a/tests/unittests/curl-runtime-shim.cpp b/tests/unittests/curl-runtime-shim.cpp new file mode 100644 index 000000000..860f020be --- /dev/null +++ b/tests/unittests/curl-runtime-shim.cpp @@ -0,0 +1,55 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// These inert stubs only satisfy loader relocations; the test never calls them. +extern "C" +{ +#define DECLARE_CURL_STUB(name) void name(); +DECLARE_CURL_STUB(curl_easy_cleanup) +DECLARE_CURL_STUB(curl_easy_getinfo) +DECLARE_CURL_STUB(curl_easy_init) +DECLARE_CURL_STUB(curl_easy_perform) +DECLARE_CURL_STUB(curl_easy_setopt) +DECLARE_CURL_STUB(curl_easy_strerror) +DECLARE_CURL_STUB(curl_global_init) +DECLARE_CURL_STUB(curl_multi_add_handle) +DECLARE_CURL_STUB(curl_multi_cleanup) +DECLARE_CURL_STUB(curl_multi_info_read) +DECLARE_CURL_STUB(curl_multi_init) +DECLARE_CURL_STUB(curl_multi_perform) +DECLARE_CURL_STUB(curl_multi_remove_handle) +DECLARE_CURL_STUB(curl_multi_setopt) +DECLARE_CURL_STUB(curl_multi_strerror) +DECLARE_CURL_STUB(curl_slist_append) +DECLARE_CURL_STUB(curl_slist_free_all) +DECLARE_CURL_STUB(curl_version_info) +#if defined(CURL_RUNTIME_SHIM_WITH_MULTI_WAIT) +DECLARE_CURL_STUB(curl_multi_wait) +#endif +#undef DECLARE_CURL_STUB + +#define DEFINE_CURL_STUB(name) void name() {} +DEFINE_CURL_STUB(curl_easy_cleanup) +DEFINE_CURL_STUB(curl_easy_getinfo) +DEFINE_CURL_STUB(curl_easy_init) +DEFINE_CURL_STUB(curl_easy_perform) +DEFINE_CURL_STUB(curl_easy_setopt) +DEFINE_CURL_STUB(curl_easy_strerror) +DEFINE_CURL_STUB(curl_global_init) +DEFINE_CURL_STUB(curl_multi_add_handle) +DEFINE_CURL_STUB(curl_multi_cleanup) +DEFINE_CURL_STUB(curl_multi_info_read) +DEFINE_CURL_STUB(curl_multi_init) +DEFINE_CURL_STUB(curl_multi_perform) +DEFINE_CURL_STUB(curl_multi_remove_handle) +DEFINE_CURL_STUB(curl_multi_setopt) +DEFINE_CURL_STUB(curl_multi_strerror) +DEFINE_CURL_STUB(curl_slist_append) +DEFINE_CURL_STUB(curl_slist_free_all) +DEFINE_CURL_STUB(curl_version_info) +#if defined(CURL_RUNTIME_SHIM_WITH_MULTI_WAIT) +DEFINE_CURL_STUB(curl_multi_wait) +#endif +#undef DEFINE_CURL_STUB +}