Files
opu/tests/test_download.cpp
T
yann64andClaude Opus 5.5 543347a1e6 core: téléchargement avec reprise, archives tar et persistance
- Downloader : HEAD + Range avec reprise, re-probe à chaque essai (URL CDN
  signées), retries bornés, fichier partiel conservé, repli sans Range,
  annulation, progression et ETA
- licence : fichier temporaire renommé à la fin ; le placeholder vide
  « licenses_<id>_<ts>.tar » renvoyé par Majestic pendant la génération de
  la licence est jeté et la requête relancée (cause du bug ENOENT de l'app
  officielle)
- archives (libarchive) : vérification complète, extraction qui ignore
  UpdateInfo.xml, refus des chemins absolus/.., liens ignorés (FAT32)
- persistance : vehicles.json compatible avec l'app officielle (BOM inclus),
  réglages + téléchargement en attente, chemins XDG / Haiku, écriture atomique
- CLI : download, verify, extract ; Ctrl-C annule proprement
- tests : faux CDN (coupures, sans Range, 4xx, annulation), tar
  ustar/gnu/pax/v7, corruption, traversal (42 cas, 322 assertions)
- validé en réel : firmware RCC 8,39 Go téléchargé, interrompu, repris et
  vérifié (ustar, 16 entrées)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WDASLCiN764v685boRVYar
2026-11-28 19:00:21 +01:00

345 lines
11 KiB
C++

#include "openpu/download.hpp"
#include "test_util.hpp"
#include <doctest/doctest.h>
#include <fstream>
using namespace openpu;
namespace fs = std::filesystem;
namespace {
/// In-memory HTTP server emulating Majestic (redirect) + CDN (Range) behaviour.
class FakeCdn final : public Transport {
public:
std::string blob;
bool supportsRange = true;
/// For each of the first N GET requests, drop the connection after this many body bytes.
std::vector<std::size_t> dropAfter;
long headStatus = 200;
long getStatus = 0; ///< forced status for GET (0 = normal behaviour)
std::string licenseBody = "LICENSE-DATA";
std::size_t chunk = 1000;
int heads = 0;
int gets = 0;
std::vector<std::string> ranges;
static constexpr const char* entryUrl = "https://majestic.test/rest/UpdateDownload?updateId=1&uin=0";
static constexpr const char* finalUrl = "https://cdn.test/BOSCH/RCC_EU/rcc-firmware/PSA_fw.tar?sig=abc";
static constexpr const char* licenseUrl = "https://majestic.test/rest/LicenseDownload?mediaVersion=1&uin=0";
HttpResponse perform(const HttpRequest& req) override
{
HttpResponse r;
if (req.url == licenseUrl) {
r.status = 200;
r.headers["content-disposition"] = "attachment; filename=license_0000.key";
r.effectiveUrl = req.url;
deliver(req, r, licenseBody);
return r;
}
if (req.method == HttpMethod::Head) {
++heads;
REQUIRE(req.url == entryUrl);
r.status = headStatus;
r.effectiveUrl = finalUrl;
r.headers["content-length"] = std::to_string(blob.size());
if (req.onHeaders)
req.onHeaders(r.status, r.headers);
return r;
}
REQUIRE(req.url == finalUrl);
const int index = gets++;
std::size_t from = 0;
std::string range;
for (const auto& [k, v] : req.headers)
if (k == "Range")
range = v;
ranges.push_back(range);
if (getStatus != 0) {
r.status = getStatus;
deliver(req, r, "error page");
return r;
}
if (!range.empty() && supportsRange) {
from = std::stoull(range.substr(6, range.find('-') - 6));
r.status = 206;
r.headers["content-range"] = "bytes " + std::to_string(from) + "-" + std::to_string(blob.size() - 1) + "/" +
std::to_string(blob.size());
} else {
r.status = 200;
}
const std::string body = blob.substr(from);
r.headers["content-length"] = std::to_string(body.size());
const std::size_t limit =
index < static_cast<int>(dropAfter.size()) ? dropAfter[static_cast<std::size_t>(index)] : body.size();
deliver(req, r, body, limit);
return r;
}
private:
void deliver(const HttpRequest& req, HttpResponse& r, const std::string& body, std::size_t limit = std::string::npos)
{
if (req.onHeaders && !req.onHeaders(r.status, r.headers))
throw TransferAborted("aborted");
const std::size_t end = std::min(limit, body.size());
for (std::size_t pos = 0; pos < end; pos += chunk) {
const std::size_t n = std::min(chunk, end - pos);
if (req.onData) {
if (!req.onData(body.data() + pos, n))
throw TransferAborted("aborted");
} else {
r.body.append(body, pos, n);
}
}
if (end < body.size())
throw NetworkError("connection reset");
}
};
DownloadOptions fastOptions()
{
DownloadOptions o;
o.retryDelay = std::chrono::milliseconds(0);
o.progressInterval = std::chrono::milliseconds(0);
return o;
}
std::string makeBlob(std::size_t n)
{
std::string s(n, '\0');
for (std::size_t i = 0; i < n; ++i)
s[i] = static_cast<char>('a' + (i * 7) % 26);
return s;
}
} // namespace
TEST_CASE("fresh download follows the redirect and names the file after the final URL")
{
TempDir dir;
FakeCdn cdn;
cdn.blob = makeBlob(10000);
Downloader dl(cdn, fastOptions());
std::vector<DownloadProgress> seen;
const auto r = dl.downloadResumable(FakeCdn::entryUrl, dir.path(), [&](const DownloadProgress& p) { seen.push_back(p); });
CHECK(r.file == dir.path() / "PSA_fw.tar");
CHECK(r.size == 10000);
CHECK_FALSE(r.alreadyComplete);
CHECK(readAll(r.file) == cdn.blob);
CHECK(cdn.ranges.front().empty()); // no Range header for a fresh file
REQUIRE_FALSE(seen.empty());
CHECK(seen.back().done == 10000);
CHECK(seen.back().total == 10000);
}
TEST_CASE("interrupted download is resumed with a Range request")
{
TempDir dir;
FakeCdn cdn;
cdn.blob = makeBlob(10000);
cdn.dropAfter = {3000, 2000};
Downloader dl(cdn, fastOptions());
const auto r = dl.downloadResumable(FakeCdn::entryUrl, dir.path());
CHECK(readAll(r.file) == cdn.blob);
REQUIRE(cdn.gets == 3);
CHECK(cdn.ranges[0].empty());
CHECK(cdn.ranges[1] == "bytes=3000-9999");
CHECK(cdn.ranges[2] == "bytes=5000-9999");
CHECK(cdn.heads == 3); // re-probed each attempt (signed CDN URLs may expire)
}
TEST_CASE("existing partial file from a previous session is continued")
{
TempDir dir;
FakeCdn cdn;
cdn.blob = makeBlob(5000);
writeAll(dir.path() / "PSA_fw.tar", cdn.blob.substr(0, 1234));
Downloader dl(cdn, fastOptions());
DownloadProgress last;
dl.downloadResumable(FakeCdn::entryUrl, dir.path(), [&](const DownloadProgress& p) { last = p; });
CHECK(readAll(dir.path() / "PSA_fw.tar") == cdn.blob);
CHECK(cdn.ranges[0] == "bytes=1234-4999");
CHECK(last.resumedFrom == 1234);
}
TEST_CASE("complete file is not downloaded again")
{
TempDir dir;
FakeCdn cdn;
cdn.blob = makeBlob(100);
writeAll(dir.path() / "PSA_fw.tar", cdn.blob);
Downloader dl(cdn, fastOptions());
const auto r = dl.downloadResumable(FakeCdn::entryUrl, dir.path());
CHECK(r.alreadyComplete);
CHECK(cdn.gets == 0);
}
TEST_CASE("server without Range support: file rewritten from the start")
{
TempDir dir;
FakeCdn cdn;
cdn.blob = makeBlob(4000);
cdn.supportsRange = false;
writeAll(dir.path() / "PSA_fw.tar", std::string(1500, 'Z')); // garbage partial
Downloader dl(cdn, fastOptions());
dl.downloadResumable(FakeCdn::entryUrl, dir.path());
CHECK(readAll(dir.path() / "PSA_fw.tar") == cdn.blob);
}
TEST_CASE("larger local file than announced is discarded")
{
TempDir dir;
FakeCdn cdn;
cdn.blob = makeBlob(100);
writeAll(dir.path() / "PSA_fw.tar", std::string(500, 'Z'));
Downloader dl(cdn, fastOptions());
dl.downloadResumable(FakeCdn::entryUrl, dir.path());
CHECK(readAll(dir.path() / "PSA_fw.tar") == cdn.blob);
}
TEST_CASE("retries are bounded and the partial file is kept")
{
TempDir dir;
FakeCdn cdn;
cdn.blob = makeBlob(10000);
cdn.dropAfter = std::vector<std::size_t>(10, 1000); // never completes... but makes progress
auto o = fastOptions();
o.maxRetries = 2;
Downloader dl(cdn, o);
try {
dl.downloadResumable(FakeCdn::entryUrl, dir.path());
FAIL("expected DownloadError");
} catch (const DownloadError& e) {
CHECK(e.kind() == DownloadError::Kind::Network);
}
CHECK(cdn.gets == 3);
CHECK(fs::file_size(dir.path() / "PSA_fw.tar") == 3000);
}
TEST_CASE("HTTP 4xx is fatal, no retry")
{
TempDir dir;
FakeCdn cdn;
cdn.blob = makeBlob(10);
cdn.headStatus = 403;
Downloader dl(cdn, fastOptions());
try {
dl.downloadResumable(FakeCdn::entryUrl, dir.path());
FAIL("expected DownloadError");
} catch (const DownloadError& e) {
CHECK(e.kind() == DownloadError::Kind::Http);
}
CHECK(cdn.heads == 1);
}
TEST_CASE("cancellation stops the transfer and keeps the partial file")
{
TempDir dir;
FakeCdn cdn;
cdn.blob = makeBlob(10000);
Downloader dl(cdn, fastOptions());
CancelToken cancel;
CHECK_THROWS_AS(dl.downloadResumable(
FakeCdn::entryUrl, dir.path(),
[&](const DownloadProgress& p) {
if (p.done >= 4000)
cancel.cancel();
},
&cancel),
Cancelled);
const auto size = fs::file_size(dir.path() / "PSA_fw.tar");
CHECK(size >= 4000);
CHECK(size < 10000);
}
TEST_CASE("small download uses Content-Disposition and a temporary file")
{
TempDir dir;
FakeCdn cdn;
Downloader dl(cdn, fastOptions());
const auto r = dl.downloadSmall(FakeCdn::licenseUrl, dir.path());
CHECK(r.file == dir.path() / "license_0000.key");
CHECK(readAll(r.file) == "LICENSE-DATA");
std::size_t count = 0;
for ([[maybe_unused]] const auto& e : fs::directory_iterator(dir.path()))
++count;
CHECK(count == 1); // no leftover .part
SUBCASE("known existing file is reused without request")
{
cdn.licenseBody = "CHANGED";
const auto again = dl.downloadSmall(FakeCdn::licenseUrl, dir.path(), std::string("license_0000.key"));
CHECK(again.alreadyComplete);
CHECK(readAll(again.file) == "LICENSE-DATA");
}
}
namespace {
/// LicenseDownload that first answers with an empty placeholder, like the real backend.
class LazyLicense final : public Transport {
public:
int calls = 0;
int emptyAnswers = 1;
HttpResponse perform(const HttpRequest& req) override
{
++calls;
HttpResponse r;
r.status = 200;
const bool empty = calls <= emptyAnswers;
r.headers["content-disposition"] =
empty ? "attachment; filename=licenses_1_20261128185520.tar" : "attachment; filename=license_ABC.key";
if (req.onHeaders && !req.onHeaders(r.status, r.headers))
throw TransferAborted("aborted");
if (!empty) {
const std::string body = "KEY";
if (req.onData && !req.onData(body.data(), body.size()))
throw TransferAborted("aborted");
}
return r;
}
};
} // namespace
TEST_CASE("empty license placeholder is discarded and the request repeated")
{
TempDir dir;
LazyLicense server;
Downloader dl(server, fastOptions());
const auto r = dl.downloadSmall("https://majestic.test/rest/LicenseDownload?x", dir.path());
CHECK(server.calls == 2);
CHECK(r.file.filename() == "license_ABC.key");
CHECK(readAll(r.file) == "KEY");
CHECK_FALSE(fs::exists(dir.path() / "licenses_1_20261128185520.tar"));
SUBCASE("gives up when it never arrives")
{
LazyLicense never;
never.emptyAnswers = 100;
auto o = fastOptions();
o.maxRetries = 3;
Downloader dl2(never, o);
CHECK_THROWS_AS(dl2.downloadSmall("https://majestic.test/rest/LicenseDownload?x", dir.path()), DownloadError);
CHECK(never.calls == 4);
}
}
TEST_CASE("remaining time estimate")
{
DownloadProgress p;
p.total = 1000;
p.resumedFrom = 200;
p.done = 600;
p.elapsed = std::chrono::seconds(4); // 400 bytes in 4 s -> 100 B/s, 400 left
REQUIRE(p.remaining().has_value());
CHECK(p.remaining()->count() == 4);
p.done = 200;
CHECK_FALSE(p.remaining().has_value());
}