// SPDX-License-Identifier: MIT #include "openpu/http.hpp" #include #include #include #include #include "openpu/version.hpp" namespace openpu { namespace { void globalInit() { static std::once_flag once; std::call_once(once, [] { curl_global_init(CURL_GLOBAL_DEFAULT); }); } struct CurlEasyDeleter { void operator()(CURL* c) const { curl_easy_cleanup(c); } }; struct CurlSlistDeleter { void operator()(curl_slist* l) const { curl_slist_free_all(l); } }; struct TransferState { const HttpRequest* request = nullptr; HttpResponse* response = nullptr; CURL* handle = nullptr; bool headersDelivered = false; bool abortedByCallback = false; }; std::string toLower(std::string s) { std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); return s; } std::size_t onHeaderLine(char* buffer, std::size_t size, std::size_t nitems, void* userdata) { auto* st = static_cast(userdata); const std::size_t len = size * nitems; std::string line(buffer, len); while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) line.pop_back(); if (line.rfind("HTTP/", 0) == 0) { // New response (first one, or the target of a redirect): reset headers. st->response->headers.clear(); return len; } const auto colon = line.find(':'); if (colon != std::string::npos) { std::string name = toLower(line.substr(0, colon)); std::string value = line.substr(colon + 1); const auto first = value.find_first_not_of(" \t"); value = first == std::string::npos ? std::string() : value.substr(first); st->response->headers[name] = value; } return len; } bool deliverHeaders(TransferState* st) { if (st->headersDelivered) return true; st->headersDelivered = true; long status = 0; curl_easy_getinfo(st->handle, CURLINFO_RESPONSE_CODE, &status); st->response->status = status; if (st->request->onHeaders && !st->request->onHeaders(status, st->response->headers)) { st->abortedByCallback = true; return false; } return true; } std::size_t onBody(char* ptr, std::size_t size, std::size_t nmemb, void* userdata) { auto* st = static_cast(userdata); const std::size_t len = size * nmemb; if (!deliverHeaders(st)) return 0; if (st->request->onData) { if (!st->request->onData(ptr, len)) { st->abortedByCallback = true; return 0; } } else { st->response->body.append(ptr, len); } return len; } /// The Majestic gateway ends bodies that have neither Content-Length nor chunked encoding by /// closing the TLS connection without close_notify. OpenSSL 3 reports that as a receive error /// ("unexpected eof while reading"), although the body is complete by HTTP/1.1 rules (the body /// is delimited by the connection close). Browsers accept it, and so do we, but only in this case. bool isCloseDelimitedEof(CURL* h, CURLcode rc, const HttpResponse& response) { if (rc != CURLE_RECV_ERROR) return false; long status = 0; curl_easy_getinfo(h, CURLINFO_RESPONSE_CODE, &status); if (status <= 0) return false; const auto& hd = response.headers; if (hd.count("content-length") != 0) return false; const auto te = hd.find("transfer-encoding"); if (te != hd.end() && toLower(te->second).find("chunked") != std::string::npos) return false; return true; } class CurlTransport final : public Transport { public: explicit CurlTransport(CurlOptions options) : options_(std::move(options)) { globalInit(); if (options_.userAgent.empty()) options_.userAgent = std::string("OpenPU/") + version(); } HttpResponse perform(const HttpRequest& request) override { std::unique_ptr handle(curl_easy_init()); if (!handle) throw NetworkError("curl_easy_init failed"); CURL* h = handle.get(); HttpResponse response; TransferState st; st.request = &request; st.response = &response; st.handle = h; std::unique_ptr headers; for (const auto& [name, value] : request.headers) { std::string line = name; line.append(": ").append(value); headers.reset(curl_slist_append(headers.release(), line.c_str())); } char errbuf[CURL_ERROR_SIZE] = {}; curl_easy_setopt(h, CURLOPT_ERRORBUFFER, errbuf); curl_easy_setopt(h, CURLOPT_URL, request.url.c_str()); curl_easy_setopt(h, CURLOPT_USERAGENT, options_.userAgent.c_str()); curl_easy_setopt(h, CURLOPT_FOLLOWLOCATION, request.followRedirects ? 1L : 0L); curl_easy_setopt(h, CURLOPT_MAXREDIRS, 10L); curl_easy_setopt(h, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(h, CURLOPT_ACCEPT_ENCODING, ""); // enable all supported encodings curl_easy_setopt(h, CURLOPT_CONNECTTIMEOUT_MS, static_cast(request.connectTimeout.count())); if (request.stallTimeout.count() > 0) { // Abort when the transfer rate stays below 1 byte/s for the stall period. curl_easy_setopt(h, CURLOPT_LOW_SPEED_LIMIT, 1L); curl_easy_setopt(h, CURLOPT_LOW_SPEED_TIME, std::max(1L, static_cast(request.stallTimeout.count() / 1000))); } curl_easy_setopt(h, CURLOPT_HEADERFUNCTION, &onHeaderLine); curl_easy_setopt(h, CURLOPT_HEADERDATA, &st); curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, &onBody); curl_easy_setopt(h, CURLOPT_WRITEDATA, &st); curl_easy_setopt(h, CURLOPT_VERBOSE, options_.verbose ? 1L : 0L); if (headers) curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers.get()); switch (request.method) { case HttpMethod::Get: curl_easy_setopt(h, CURLOPT_HTTPGET, 1L); break; case HttpMethod::Head: curl_easy_setopt(h, CURLOPT_NOBODY, 1L); break; case HttpMethod::Post: curl_easy_setopt(h, CURLOPT_POST, 1L); curl_easy_setopt(h, CURLOPT_POSTFIELDS, request.body.c_str()); curl_easy_setopt(h, CURLOPT_POSTFIELDSIZE_LARGE, static_cast(request.body.size())); break; } const CURLcode rc = curl_easy_perform(h); if (st.abortedByCallback) throw TransferAborted("transfer aborted"); if (rc != CURLE_OK && !isCloseDelimitedEof(h, rc, response)) { const std::string detail = errbuf[0] != '\0' ? errbuf : curl_easy_strerror(rc); throw NetworkError(detail); } // Responses without body (HEAD, 204, empty 200) never reached onBody. if (!deliverHeaders(&st)) throw TransferAborted("transfer aborted"); char* effective = nullptr; curl_easy_getinfo(h, CURLINFO_EFFECTIVE_URL, &effective); if (effective != nullptr) response.effectiveUrl = effective; return response; } private: CurlOptions options_; }; } // namespace std::unique_ptr makeCurlTransport(CurlOptions options) { return std::make_unique(std::move(options)); } } // namespace openpu