Skip to content

Commit

Permalink
Fix for possible leaks of curl types (#6719)
Browse files Browse the repository at this point in the history
  • Loading branch information
achamayou authored Jan 6, 2025
1 parent 571dfdb commit 1083711
Showing 1 changed file with 42 additions and 12 deletions.
54 changes: 42 additions & 12 deletions src/snapshots/fetch.h
Original file line number Diff line number Diff line change
Expand Up @@ -116,16 +116,49 @@ namespace snapshots
HeaderMap headers;
};

static inline SimpleHTTPResponse make_curl_request(
const SimpleHTTPRequest& request)
class UniqueCURL
{
CURL* curl;
protected:
std::unique_ptr<CURL, void (*)(CURL*)> p;

public:
UniqueCURL() : p(curl_easy_init(), [](auto x) { curl_easy_cleanup(x); })
{
if (!p.get())
{
throw std::runtime_error("Error initialising curl easy request");
}
}

curl = curl_easy_init();
if (!curl)
operator CURL*() const
{
throw std::runtime_error("Error initialising curl easy request");
return p.get();
}
};

class UniqueSlist
{
protected:
std::unique_ptr<curl_slist, void (*)(curl_slist*)> p;

public:
UniqueSlist() : p(nullptr, [](auto x) { curl_slist_free_all(x); }) {}

void append(const char* str)
{
p.reset(curl_slist_append(p.release(), str));
}

curl_slist* get() const
{
return p.get();
}
};

static inline SimpleHTTPResponse make_curl_request(
const SimpleHTTPRequest& request)
{
UniqueCURL curl;

CHECK_CURL_EASY_SETOPT(curl, CURLOPT_URL, request.url.c_str());
if (request.method == HTTP_HEAD)
Expand All @@ -148,13 +181,13 @@ namespace snapshots

curl_easy_setopt(curl, CURLOPT_CAINFO, request.ca_path.c_str());

curl_slist* list = nullptr;
UniqueSlist list;
for (const auto& [k, v] : request.headers)
{
list = curl_slist_append(list, fmt::format("{}: {}", k, v).c_str());
list.append(fmt::format("{}: {}", k, v).c_str());
}

CHECK_CURL_EASY_SETOPT(curl, CURLOPT_HTTPHEADER, list);
CHECK_CURL_EASY_SETOPT(curl, CURLOPT_HTTPHEADER, list.get());

if (request.body_handler != nullptr)
{
Expand All @@ -176,9 +209,6 @@ namespace snapshots
request.url,
response.status_code);

curl_slist_free_all(list);
curl_easy_cleanup(curl);

return response;
}

Expand Down

0 comments on commit 1083711

Please sign in to comment.