Skip to content

Commit 297ddd7

Browse files
committed
Fix download to file
The RAII file-handle wrapper was created in the inner scope causing the file to be closed before cURL uses it. Move to outer function to ensure validity.
1 parent 51196ff commit 297ddd7

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

src/s25update.cpp

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ std::string EscapeFile(const bfs::path& file)
193193
/**
194194
* httpdownload function (to std::string or to file, with or without progressbar)
195195
*/
196-
bool DoDownloadFile(const std::string& url, const std::variant<std::string*, bfs::path>& target,
196+
bool DoDownloadFile(const std::string& url, const std::variant<std::string*, FILE*>& target,
197197
std::string* progress = nullptr)
198198
{
199199
EasyCurl curl;
@@ -215,17 +215,10 @@ bool DoDownloadFile(const std::string& url, const std::variant<std::string*, bfs
215215
#endif
216216
}
217217

218-
if(std::holds_alternative<bfs::path>(target))
218+
if(std::holds_alternative<FILE*>(target))
219219
{
220220
curl.setOpt(CURLOPT_WRITEFUNCTION, WriteCallback);
221-
const auto& targetPath = std::get<bfs::path>(target);
222-
s25util::file_handle target_fh(boost::nowide::fopen(targetPath.string().c_str(), "wb"));
223-
if(!target_fh)
224-
{
225-
bnw::cerr << "Can't open file " << targetPath << "!" << std::endl;
226-
return false;
227-
}
228-
curl.setOpt(CURLOPT_WRITEDATA, static_cast<void*>(*target_fh));
221+
curl.setOpt(CURLOPT_WRITEDATA, static_cast<void*>(std::get<FILE*>(target)));
229222
} else
230223
{
231224
curl.setOpt(CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
@@ -244,7 +237,13 @@ bool DoDownloadFile(const std::string& url, const std::variant<std::string*, bfs
244237

245238
bool DownloadFile(const std::string& url, const bfs::path& path, std::string progress = "")
246239
{
247-
return DoDownloadFile(url, path, &progress);
240+
s25util::file_handle target_fh(boost::nowide::fopen(path.string().c_str(), "wb"));
241+
if(!target_fh)
242+
{
243+
bnw::cerr << "Can't open file " << path << "!" << std::endl;
244+
return false;
245+
}
246+
return DoDownloadFile(url, *target_fh, &progress);
248247
}
249248

250249
std::optional<std::string> DownloadFile(const std::string& url)

0 commit comments

Comments
 (0)