2021-03-26 23:18:51 +01:00
|
|
|
#include "cpr/curlholder.h"
|
|
|
|
#include <cassert>
|
|
|
|
|
|
|
|
namespace cpr {
|
|
|
|
CurlHolder::CurlHolder() {
|
|
|
|
/**
|
|
|
|
* Allow multithreaded access to CPR by locking curl_easy_init().
|
|
|
|
* curl_easy_init() is not thread safe.
|
|
|
|
* References:
|
|
|
|
* https://curl.haxx.se/libcurl/c/curl_easy_init.html
|
|
|
|
* https://curl.haxx.se/libcurl/c/threadsafe.html
|
|
|
|
**/
|
2023-08-05 20:31:33 +02:00
|
|
|
curl_easy_init_mutex_().lock();
|
|
|
|
// NOLINTNEXTLINE (cppcoreguidelines-prefer-member-initializer) since we need it to happen inside the lock
|
2021-03-26 23:18:51 +01:00
|
|
|
handle = curl_easy_init();
|
2023-08-05 20:31:33 +02:00
|
|
|
curl_easy_init_mutex_().unlock();
|
2021-03-26 23:18:51 +01:00
|
|
|
|
|
|
|
assert(handle);
|
|
|
|
} // namespace cpr
|
|
|
|
|
|
|
|
CurlHolder::~CurlHolder() {
|
|
|
|
curl_slist_free_all(chunk);
|
2023-08-05 20:31:33 +02:00
|
|
|
curl_slist_free_all(resolveCurlList);
|
|
|
|
curl_mime_free(multipart);
|
2021-07-02 16:44:48 +02:00
|
|
|
curl_easy_cleanup(handle);
|
2021-03-26 23:18:51 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
std::string CurlHolder::urlEncode(const std::string& s) const {
|
|
|
|
assert(handle);
|
2023-08-05 20:31:33 +02:00
|
|
|
char* output = curl_easy_escape(handle, s.c_str(), static_cast<int>(s.length()));
|
2021-03-26 23:18:51 +01:00
|
|
|
if (output) {
|
|
|
|
std::string result = output;
|
|
|
|
curl_free(output);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
return "";
|
|
|
|
}
|
|
|
|
|
|
|
|
std::string CurlHolder::urlDecode(const std::string& s) const {
|
|
|
|
assert(handle);
|
2023-08-05 20:31:33 +02:00
|
|
|
char* output = curl_easy_unescape(handle, s.c_str(), static_cast<int>(s.length()), nullptr);
|
2021-03-26 23:18:51 +01:00
|
|
|
if (output) {
|
|
|
|
std::string result = output;
|
|
|
|
curl_free(output);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
return "";
|
|
|
|
}
|
|
|
|
} // namespace cpr
|