diff --git a/lib/http/HttpClient_Curl.hpp b/lib/http/HttpClient_Curl.hpp index eac40ad13..fe712cc8c 100644 --- a/lib/http/HttpClient_Curl.hpp +++ b/lib/http/HttpClient_Curl.hpp @@ -33,8 +33,18 @@ #include #include +#include +#if defined(__GLIBC__) +#include +#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" @@ -45,6 +55,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 @@ -78,6 +100,79 @@ 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; +} + +#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. + * + * 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 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 PinCurlModuleForQuickExit() 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; + } +#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) + { + 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. @@ -293,7 +388,6 @@ class CurlHttpOperation { return; } -#if LIBCURL_VERSION_NUM >= 0x075000 const curl_version_info_data* versionInfo = curl_version_info(CURLVERSION_NOW); if (versionInfo == nullptr) { @@ -303,8 +397,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()) || @@ -551,7 +664,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); @@ -803,6 +917,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; @@ -961,6 +1076,91 @@ 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 +#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) + { + return CURLE_OUT_OF_MEMORY; + } + // 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); + 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; + } + const CURLMcode pollResult = multiPoll != nullptr + ? multiPoll(multi, nullptr, 0, sliceMs, nullptr) + : multiWait(multi, nullptr, 0, sliceMs, nullptr); + if (pollResult != 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/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() diff --git a/tests/unittests/CMakeLists.txt b/tests/unittests/CMakeLists.txt index ff682427b..15cb34021 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() @@ -159,3 +163,99 @@ 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() + +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/HttpClientCurlTests.cpp b/tests/unittests/HttpClientCurlTests.cpp index 1d6236e19..501d38cb6 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,200 @@ 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. +#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: + 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); + 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(); + 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; + { + 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); + + // 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__ + #endif // MATSDK_PAL_CPP11 && !_MSC_VER && HAVE_MAT_DEFAULT_HTTP_CLIENT 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..7b7d187b3 --- /dev/null +++ b/tests/unittests/curl-module-unload-test.cpp @@ -0,0 +1,333 @@ +// +// 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 char* hostname) const + { + return "http://" + std::string(hostname) + ":" + 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; + } + + 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 realGetAddrInfo(node, service, hints, result); +} + +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("idle-worker.invalid").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, "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; + } + + 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; +} 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 +}