| 1 | // Copyright 2017 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "Common/HttpRequest.h" |
| 5 | |
| 6 | #include <chrono> |
| 7 | #include <cstddef> |
| 8 | #include <mutex> |
| 9 | |
| 10 | #include <curl/curl.h> |
| 11 | |
| 12 | #include "Common/Logging/Log.h" |
| 13 | #include "Common/ScopeGuard.h" |
| 14 | #include "Common/StringUtil.h" |
| 15 | |
| 16 | namespace Common |
| 17 | { |
| 18 | class HttpRequest::Impl final |
| 19 | { |
| 20 | public: |
| 21 | enum class Method |
| 22 | { |
| 23 | GET, |
| 24 | POST, |
| 25 | }; |
| 26 | |
| 27 | explicit Impl(std::chrono::milliseconds timeout_ms, ProgressCallback callback); |
| 28 | |
| 29 | bool IsValid() const; |
| 30 | std::string GetHeaderValue(std::string_view name) const; |
| 31 | void SetCookies(const std::string& cookies); |
| 32 | void UseIPv4(); |
| 33 | void FollowRedirects(long max); |
| 34 | s32 GetLastResponseCode(); |
| 35 | Response Fetch(const std::string& url, Method method, const Headers& headers, const u8* payload, |
| 36 | size_t size, AllowedReturnCodes codes = AllowedReturnCodes::Ok_Only, |
| 37 | std::span<Multiform> multiform = {}); |
| 38 | |
| 39 | static int CurlProgressCallback(Impl* impl, curl_off_t dltotal, curl_off_t dlnow, |
| 40 | curl_off_t ultotal, curl_off_t ulnow); |
| 41 | std::string EscapeComponent(const std::string& string); |
| 42 | |
| 43 | private: |
| 44 | static inline std::once_flag s_curl_was_initialized; |
| 45 | ProgressCallback m_callback; |
| 46 | Headers m_response_headers; |
| 47 | std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> m_curl{nullptr, curl_easy_cleanup}; |
| 48 | std::string m_error_string; |
| 49 | }; |
| 50 | |
| 51 | HttpRequest::HttpRequest(std::chrono::milliseconds timeout_ms, ProgressCallback callback) |
| 52 | : m_impl(std::make_unique<Impl>(timeout_ms, std::move(callback))) |
| 53 | { |
| 54 | } |
| 55 | |
| 56 | HttpRequest::~HttpRequest() = default; |
| 57 | |
| 58 | bool HttpRequest::IsValid() const |
| 59 | { |
| 60 | return m_impl->IsValid(); |
| 61 | } |
| 62 | |
| 63 | void HttpRequest::SetCookies(const std::string& cookies) |
| 64 | { |
| 65 | m_impl->SetCookies(cookies); |
| 66 | } |
| 67 | |
| 68 | void HttpRequest::UseIPv4() |
| 69 | { |
| 70 | m_impl->UseIPv4(); |
| 71 | } |
| 72 | |
| 73 | void HttpRequest::FollowRedirects(long max) |
| 74 | { |
| 75 | m_impl->FollowRedirects(max); |
| 76 | } |
| 77 | |
| 78 | std::string HttpRequest::EscapeComponent(const std::string& string) |
| 79 | { |
| 80 | return m_impl->EscapeComponent(string); |
| 81 | } |
| 82 | |
| 83 | s32 HttpRequest::GetLastResponseCode() const |
| 84 | { |
| 85 | return m_impl->GetLastResponseCode(); |
| 86 | } |
| 87 | |
| 88 | std::string HttpRequest::GetHeaderValue(std::string_view name) const |
| 89 | { |
| 90 | return m_impl->GetHeaderValue(name); |
| 91 | } |
| 92 | |
| 93 | HttpRequest::Response HttpRequest::Get(const std::string& url, const Headers& headers, |
| 94 | AllowedReturnCodes codes) |
| 95 | { |
| 96 | return m_impl->Fetch(url, Impl::Method::GET, headers, nullptr, 0, codes); |
| 97 | } |
| 98 | |
| 99 | HttpRequest::Response HttpRequest::Post(const std::string& url, std::span<const u8> payload, |
| 100 | const Headers& headers, AllowedReturnCodes codes) |
| 101 | { |
| 102 | return m_impl->Fetch(url, Impl::Method::POST, headers, payload.data(), payload.size(), codes); |
| 103 | } |
| 104 | |
| 105 | HttpRequest::Response HttpRequest::Post(const std::string& url, std::string_view payload, |
| 106 | const Headers& headers, AllowedReturnCodes codes) |
| 107 | { |
| 108 | return m_impl->Fetch(url, Impl::Method::POST, headers, |
| 109 | reinterpret_cast<const u8*>(payload.data()), payload.size(), codes); |
| 110 | } |
| 111 | |
| 112 | int HttpRequest::Impl::CurlProgressCallback(Impl* impl, curl_off_t dltotal, curl_off_t dlnow, |
| 113 | curl_off_t ultotal, curl_off_t ulnow) |
| 114 | { |
| 115 | // Abort if callback isn't true |
| 116 | return !impl->m_callback(static_cast<s64>(dltotal), static_cast<s64>(dlnow), |
| 117 | static_cast<s64>(ultotal), static_cast<s64>(ulnow)); |
| 118 | } |
| 119 | |
| 120 | HttpRequest::Impl::Impl(std::chrono::milliseconds timeout_ms, ProgressCallback callback) |
| 121 | : m_callback(std::move(callback)) |
| 122 | { |
| 123 | std::call_once(s_curl_was_initialized, [] { curl_global_init(CURL_GLOBAL_DEFAULT); }); |
| 124 | |
| 125 | m_curl.reset(curl_easy_init()); |
| 126 | if (!m_curl) |
| 127 | return; |
| 128 | |
| 129 | curl_easy_setopt(m_curl.get(), CURLOPT_NOPROGRESS, m_callback == nullptr); |
| 130 | |
| 131 | if (m_callback) |
| 132 | { |
| 133 | curl_easy_setopt(m_curl.get(), CURLOPT_PROGRESSDATA, this); |
| 134 | curl_easy_setopt(m_curl.get(), CURLOPT_XFERINFOFUNCTION, CurlProgressCallback); |
| 135 | } |
| 136 | |
| 137 | // Set up error buffer |
| 138 | m_error_string.resize(CURL_ERROR_SIZE); |
| 139 | curl_easy_setopt(m_curl.get(), CURLOPT_ERRORBUFFER, m_error_string.data()); |
| 140 | |
| 141 | // libcurl may not have been built with async DNS support, so we disable |
| 142 | // signal handlers to avoid a possible and likely crash if a resolve times out. |
| 143 | curl_easy_setopt(m_curl.get(), CURLOPT_NOSIGNAL, true); |
| 144 | curl_easy_setopt(m_curl.get(), CURLOPT_CONNECTTIMEOUT_MS, static_cast<long>(timeout_ms.count())); |
| 145 | // Sadly CURLOPT_LOW_SPEED_TIME doesn't have a millisecond variant so we have to use seconds |
| 146 | curl_easy_setopt( |
| 147 | m_curl.get(), CURLOPT_LOW_SPEED_TIME, |
| 148 | static_cast<long>(std::chrono::duration_cast<std::chrono::seconds>(timeout_ms).count())); |
| 149 | curl_easy_setopt(m_curl.get(), CURLOPT_LOW_SPEED_LIMIT, 1); |
| 150 | } |
| 151 | |
| 152 | bool HttpRequest::Impl::IsValid() const |
| 153 | { |
| 154 | return m_curl != nullptr; |
| 155 | } |
| 156 | |
| 157 | s32 HttpRequest::Impl::GetLastResponseCode() |
| 158 | { |
| 159 | long response_code{}; |
| 160 | curl_easy_getinfo(m_curl.get(), CURLINFO_RESPONSE_CODE, &response_code); |
| 161 | return static_cast<s32>(response_code); |
| 162 | } |
| 163 | |
| 164 | void HttpRequest::Impl::SetCookies(const std::string& cookies) |
| 165 | { |
| 166 | curl_easy_setopt(m_curl.get(), CURLOPT_COOKIE, cookies.c_str()); |
| 167 | } |
| 168 | |
| 169 | void HttpRequest::Impl::UseIPv4() |
| 170 | { |
| 171 | curl_easy_setopt(m_curl.get(), CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); |
| 172 | } |
| 173 | |
| 174 | HttpRequest::Response HttpRequest::PostMultiform(const std::string& url, |
| 175 | std::span<Multiform> multiform, |
| 176 | const Headers& headers, AllowedReturnCodes codes) |
| 177 | { |
| 178 | return m_impl->Fetch(url, Impl::Method::POST, headers, nullptr, 0, codes, multiform); |
| 179 | } |
| 180 | |
| 181 | void HttpRequest::Impl::FollowRedirects(long max) |
| 182 | { |
| 183 | curl_easy_setopt(m_curl.get(), CURLOPT_FOLLOWLOCATION, 1); |
| 184 | curl_easy_setopt(m_curl.get(), CURLOPT_MAXREDIRS, max); |
| 185 | } |
| 186 | |
| 187 | std::string HttpRequest::Impl::GetHeaderValue(std::string_view name) const |
| 188 | { |
| 189 | for (const auto& [key, value] : m_response_headers) |
| 190 | { |
| 191 | if (key == name) |
| 192 | return value.value(); |
| 193 | } |
| 194 | |
| 195 | return {}; |
| 196 | } |
| 197 | |
| 198 | std::string HttpRequest::Impl::EscapeComponent(const std::string& string) |
| 199 | { |
| 200 | char* escaped = curl_easy_escape(m_curl.get(), string.c_str(), static_cast<int>(string.size())); |
| 201 | std::string escaped_str(escaped); |
| 202 | curl_free(escaped); |
| 203 | |
| 204 | return escaped_str; |
| 205 | } |
| 206 | |
| 207 | static size_t CurlWriteCallback(char* data, size_t size, size_t nmemb, void* userdata) |
| 208 | { |
| 209 | auto* buffer = static_cast<std::vector<u8>*>(userdata); |
| 210 | const size_t actual_size = size * nmemb; |
| 211 | buffer->insert(buffer->end(), data, data + actual_size); |
| 212 | return actual_size; |
| 213 | } |
| 214 | |
| 215 | static size_t header_callback(char* buffer, size_t size, size_t nitems, void* userdata) |
| 216 | { |
| 217 | auto* headers = static_cast<HttpRequest::Headers*>(userdata); |
| 218 | std::string_view full_buffer = std::string_view{buffer, nitems}; |
| 219 | const size_t colon_pos = full_buffer.find(':'); |
| 220 | if (colon_pos == std::string::npos) |
| 221 | return nitems * size; |
| 222 | |
| 223 | const std::string_view key = full_buffer.substr(0, colon_pos); |
| 224 | const std::string_view value = StripWhitespace(full_buffer.substr(colon_pos + 1)); |
| 225 | |
| 226 | headers->emplace(std::string{key}, std::string{value}); |
| 227 | return nitems * size; |
| 228 | } |
| 229 | |
| 230 | HttpRequest::Response HttpRequest::Impl::Fetch(const std::string& url, Method method, |
| 231 | const Headers& headers, const u8* payload, |
| 232 | size_t size, AllowedReturnCodes codes, |
| 233 | std::span<Multiform> multiform) |
| 234 | { |
| 235 | m_response_headers.clear(); |
| 236 | curl_easy_setopt(m_curl.get(), CURLOPT_POST, method == Method::POST); |
| 237 | curl_easy_setopt(m_curl.get(), CURLOPT_URL, url.c_str()); |
| 238 | if (method == Method::POST && multiform.empty()) |
| 239 | { |
| 240 | curl_easy_setopt(m_curl.get(), CURLOPT_POSTFIELDS, payload); |
| 241 | curl_easy_setopt(m_curl.get(), CURLOPT_POSTFIELDSIZE, size); |
| 242 | } |
| 243 | |
| 244 | curl_mime* form = nullptr; |
| 245 | Common::ScopeGuard multiform_guard{[&form] { curl_mime_free(form); }}; |
| 246 | if (!multiform.empty()) |
| 247 | { |
| 248 | form = curl_mime_init(m_curl.get()); |
| 249 | for (const auto& value : multiform) |
| 250 | { |
| 251 | curl_mimepart* part = curl_mime_addpart(form); |
| 252 | curl_mime_name(part, value.name.c_str()); |
| 253 | curl_mime_data(part, value.data.c_str(), value.data.size()); |
| 254 | } |
| 255 | |
| 256 | curl_easy_setopt(m_curl.get(), CURLOPT_MIMEPOST, form); |
| 257 | } |
| 258 | |
| 259 | curl_slist* list = nullptr; |
| 260 | Common::ScopeGuard list_guard{[&list] { curl_slist_free_all(list); }}; |
| 261 | for (const auto& [name, value] : headers) |
| 262 | { |
| 263 | if (!value) |
| 264 | list = curl_slist_append(list, (name + ':').c_str()); |
| 265 | else if (value->empty()) |
| 266 | list = curl_slist_append(list, (name + ';').c_str()); |
| 267 | else |
| 268 | list = curl_slist_append(list, (name + ": " + *value).c_str()); |
| 269 | } |
| 270 | curl_easy_setopt(m_curl.get(), CURLOPT_HTTPHEADER, list); |
| 271 | |
| 272 | curl_easy_setopt(m_curl.get(), CURLOPT_HEADERFUNCTION, header_callback); |
| 273 | curl_easy_setopt(m_curl.get(), CURLOPT_HEADERDATA, static_cast<void*>(&m_response_headers)); |
| 274 | |
| 275 | std::vector<u8> buffer; |
| 276 | curl_easy_setopt(m_curl.get(), CURLOPT_WRITEFUNCTION, CurlWriteCallback); |
| 277 | curl_easy_setopt(m_curl.get(), CURLOPT_WRITEDATA, &buffer); |
| 278 | |
| 279 | const char* type = method == Method::POST ? "POST" : "GET"; |
| 280 | const CURLcode res = curl_easy_perform(m_curl.get()); |
| 281 | if (res != CURLE_OK) |
| 282 | { |
| 283 | ERROR_LOG_FMT(COMMON, "Failed to {} {}: {}", type, url, m_error_string); |
| 284 | return {}; |
| 285 | } |
| 286 | |
| 287 | if (codes == AllowedReturnCodes::All) |
| 288 | return buffer; |
| 289 | |
| 290 | long response_code = 0; |
| 291 | curl_easy_getinfo(m_curl.get(), CURLINFO_RESPONSE_CODE, &response_code); |
| 292 | if (response_code != 200) |
| 293 | { |
| 294 | if (buffer.empty()) |
| 295 | { |
| 296 | ERROR_LOG_FMT(COMMON, "Failed to {} {}: server replied with code {}", type, url, |
| 297 | response_code); |
| 298 | } |
| 299 | else |
| 300 | { |
| 301 | ERROR_LOG_FMT(COMMON, "Failed to {} {}: server replied with code {} and body\n\x1b[0m{:.{}}", |
| 302 | type, url, response_code, reinterpret_cast<char*>(buffer.data()), |
| 303 | static_cast<int>(buffer.size())); |
| 304 | } |
| 305 | return {}; |
| 306 | } |
| 307 | |
| 308 | return buffer; |
| 309 | } |
| 310 | } // namespace Common |