Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
204 changes: 202 additions & 2 deletions lib/http/HttpClient_Curl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,18 @@
#include <poll.h>
#include <curl/curl.h>

#include <dlfcn.h>
#if defined(__GLIBC__)
#include <link.h>
#endif
#include <unistd.h>

#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
Comment thread
bmehta001 marked this conversation as resolved.
Resolved
#endif

#include "IHttpClient.hpp"
#include "IBoundedHttpClientCancel.hpp"
#include "pal/PAL.hpp"
Expand All @@ -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<CURLoption>(CURLOPTTYPE_LONG + 322) // libcurl 7.87.0
#define MATSDK_CURLMOPT_QUICK_EXIT static_cast<CURLMoption>(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

Expand Down Expand Up @@ -78,6 +100,79 @@ inline CURLcode EnsureCurlGlobalInit() noexcept
return initResult;
}

struct CurlModulePinState
{
std::once_flag once;
std::atomic<bool> 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<const void*>(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<const void*>(&curl_easy_init), &info) == 0 || info.dli_fname == nullptr)
Comment thread
Copilot marked this conversation as resolved.
Resolved
{
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);
Comment thread
bmehta001 marked this conversation as resolved.
Resolved
}
});
#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.
Expand Down Expand Up @@ -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)
{
Expand All @@ -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()) ||
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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.
*
Expand Down
1 change: 1 addition & 0 deletions lib/include/public/ICdsFactory.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include <functional>
#include <map>
#include <memory>
#include <stdint.h>
#include <string>
#include <vector>

Expand Down
9 changes: 8 additions & 1 deletion tests/build-runner-tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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()
Loading
Loading