- interface gtkmm-4 : véhicules, ajout par VIN, mises à jour, dossier, téléchargement avec reprise et arrêt, choix de la clé, confirmation, écriture avec progression, fin avec guide d'installation ; travail dans un thread, résultats renvoyés via Glib::Dispatcher - préférences : dossier de téléchargement, langue (système par défaut), recherche automatique de nouvelle version d'OpenPU - recherche de nouvelle version (releases GitHub, format tags Gitea accepté) avec ouverture de la page dans le navigateur ; openpu-cli app-update - versions : project(VERSION) + git describe régénéré à chaque build, openpu-cli --version, À propos, User-Agent, CHANGELOG, tools/release.sh (étiquette annotée, push vers tous les remotes, release GitHub) - traductions gettext : textes anglais, fr.po complet (96 chaînes), extracteur de secours sans xgettext - core : module job (téléchargement licence/fw/carte), liens des guides PDF, ordre des véhicules conservé (ordered_json) - licence MIT (LICENSE, en-têtes SPDX) ; dépôt principal sur GitHub - validé dans WSLg : parcours complet jusqu'à l'écriture d'une clé loop (FAT32 propre, fichiers téléchargés supprimés) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WDASLCiN764v685boRVYar
212 lines
7.2 KiB
C++
212 lines
7.2 KiB
C++
// SPDX-License-Identifier: MIT
|
|
#include "openpu/http.hpp"
|
|
|
|
#include <algorithm>
|
|
#include <cctype>
|
|
#include <curl/curl.h>
|
|
#include <mutex>
|
|
|
|
#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<char>(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<TransferState*>(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<TransferState*>(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<CURL, CurlEasyDeleter> 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<curl_slist, CurlSlistDeleter> 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<long>(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<long>(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<curl_off_t>(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<Transport> makeCurlTransport(CurlOptions options)
|
|
{
|
|
return std::make_unique<CurlTransport>(std::move(options));
|
|
}
|
|
|
|
} // namespace openpu
|