Skip to content

Commit 1083711

Browse files
authored
Fix for possible leaks of curl types (#6719)
1 parent 571dfdb commit 1083711

File tree

1 file changed

+42
-12
lines changed

1 file changed

+42
-12
lines changed

src/snapshots/fetch.h

Lines changed: 42 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -116,16 +116,49 @@ namespace snapshots
116116
HeaderMap headers;
117117
};
118118

119-
static inline SimpleHTTPResponse make_curl_request(
120-
const SimpleHTTPRequest& request)
119+
class UniqueCURL
121120
{
122-
CURL* curl;
121+
protected:
122+
std::unique_ptr<CURL, void (*)(CURL*)> p;
123+
124+
public:
125+
UniqueCURL() : p(curl_easy_init(), [](auto x) { curl_easy_cleanup(x); })
126+
{
127+
if (!p.get())
128+
{
129+
throw std::runtime_error("Error initialising curl easy request");
130+
}
131+
}
123132

124-
curl = curl_easy_init();
125-
if (!curl)
133+
operator CURL*() const
126134
{
127-
throw std::runtime_error("Error initialising curl easy request");
135+
return p.get();
128136
}
137+
};
138+
139+
class UniqueSlist
140+
{
141+
protected:
142+
std::unique_ptr<curl_slist, void (*)(curl_slist*)> p;
143+
144+
public:
145+
UniqueSlist() : p(nullptr, [](auto x) { curl_slist_free_all(x); }) {}
146+
147+
void append(const char* str)
148+
{
149+
p.reset(curl_slist_append(p.release(), str));
150+
}
151+
152+
curl_slist* get() const
153+
{
154+
return p.get();
155+
}
156+
};
157+
158+
static inline SimpleHTTPResponse make_curl_request(
159+
const SimpleHTTPRequest& request)
160+
{
161+
UniqueCURL curl;
129162

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

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

151-
curl_slist* list = nullptr;
184+
UniqueSlist list;
152185
for (const auto& [k, v] : request.headers)
153186
{
154-
list = curl_slist_append(list, fmt::format("{}: {}", k, v).c_str());
187+
list.append(fmt::format("{}: {}", k, v).c_str());
155188
}
156189

157-
CHECK_CURL_EASY_SETOPT(curl, CURLOPT_HTTPHEADER, list);
190+
CHECK_CURL_EASY_SETOPT(curl, CURLOPT_HTTPHEADER, list.get());
158191

159192
if (request.body_handler != nullptr)
160193
{
@@ -176,9 +209,6 @@ namespace snapshots
176209
request.url,
177210
response.status_code);
178211

179-
curl_slist_free_all(list);
180-
curl_easy_cleanup(curl);
181-
182212
return response;
183213
}
184214

0 commit comments

Comments
 (0)