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
This commit is contained in:
yann64andClaude Opus 5.5 committed 2026-11-28 19:00:21 +01:00
1 parent 95704f9882
commit 543347a1e6
17 files changed
+2168 -40

No files matched your search

+211 -36
View File
@@ -1,23 +1,43 @@
// openpu-cli — command-line front-end of libopenpu.
#include "openpu/api_client.hpp"
#include "openpu/archive.hpp"
#include "openpu/download.hpp"
#include "openpu/storage.hpp"
#include "openpu/vin.hpp"
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
namespace {
namespace fs = std::filesystem;
openpu::CancelToken gCancel;
extern "C" void onSignal(int /*sig*/)
{
gCancel.cancel();
}
void usage()
{
std::cerr << "usage: openpu-cli [--verbose] <command> [args]\n"
"\n"
"commands:\n"
" check <VIN> identify the head unit and list available updates\n"
" raw-devices <VIN> print the raw devices/{VIN} response\n"
" raw-updates <VIN> print the raw getAvailableUpdate response (all software types)\n"
" check <VIN> identify the head unit and list available updates\n"
" download <VIN> [--dir D] [--firmware] [--map]\n"
" download license + updates (both kinds by default),\n"
" resuming partial files\n"
" verify <file.tar> check the integrity of an update archive\n"
" extract <file.tar> <dir> extract an update archive (skips UpdateInfo.xml)\n"
" raw-devices <VIN> print the raw devices/{VIN} response\n"
" raw-updates <VIN> print the raw getAvailableUpdate response\n"
"\n"
"environment: OPENPU_DEVICES_URL, OPENPU_UPDATES_URL, OPENPU_CLIENT_ID,\n"
" http_proxy, https_proxy, no_proxy\n";
@@ -37,14 +57,22 @@ std::string humanSize(std::uint64_t bytes)
return buf;
}
std::string duration(std::chrono::seconds s)
{
const auto total = static_cast<long long>(s.count());
char buf[32];
(void)std::snprintf(buf, sizeof buf, "%lld:%02lld:%02lld", total / 3600, (total / 60) % 60, total % 60);
return buf;
}
void printUpdate(const char* label, const std::optional<openpu::UpdateInfo>& u)
{
if (!u) {
std::cout << label << ": none\n";
return;
}
std::cout << label << ": " << u->version << " (" << u->softwareType << ", " << humanSize(u->size)
<< ", " << (u->date.empty() ? "no date" : u->date) << ")\n";
std::cout << label << ": " << u->version << " (" << u->softwareType << ", " << humanSize(u->size) << ", "
<< (u->date.empty() ? "no date" : u->date) << ")\n";
}
int printRaw(const openpu::HttpResponse& r)
@@ -54,56 +82,203 @@ int printRaw(const openpu::HttpResponse& r)
return r.status >= 200 && r.status < 300 ? 0 : 1;
}
} // namespace
void progressLine(const std::string& label, std::uint64_t done, std::uint64_t total, const std::string& extra)
{
const double pct = total > 0 ? 100.0 * static_cast<double>(done) / static_cast<double>(total) : 0.0;
(void)std::fprintf(stderr, "\r%s %5.1f%% %s / %s %s ", label.c_str(), pct, humanSize(done).c_str(),
humanSize(total).c_str(), extra.c_str());
(void)std::fflush(stderr);
}
int main(int argc, char** argv)
struct Context {
std::unique_ptr<openpu::Transport> transport;
std::unique_ptr<openpu::ApiClient> api;
};
/// Identifies the vehicle; prints a message and returns Unknown when it cannot be updated.
openpu::HeadUnitType identify(openpu::ApiClient& api, const std::string& vin)
{
const openpu::VehicleCheck check = api.checkVehicle(vin);
if (!check.exists) {
std::cout << "vehicle not found\n";
return openpu::HeadUnitType::Unknown;
}
if (check.type == openpu::HeadUnitType::Unknown) {
std::cout << "vehicle found, but its head unit is not supported\n";
return check.type;
}
std::cout << "head unit: " << openpu::headUnitTypeName(check.type) << "\nguide: " << check.guideKey << '\n';
return check.type;
}
int cmdCheck(Context& ctx, const std::string& vin)
{
const auto type = identify(*ctx.api, vin);
if (type == openpu::HeadUnitType::Unknown)
return 1;
const openpu::AvailableUpdates updates = ctx.api->getUpdates(vin, type);
printUpdate("firmware", updates.firmware);
printUpdate("map", updates.map);
return 0;
}
int cmdDownload(Context& ctx, const std::string& vin, const std::vector<std::string>& opts)
{
fs::path dir;
bool wantFirmware = false;
bool wantMap = false;
for (std::size_t i = 0; i < opts.size(); ++i) {
if (opts[i] == "--dir" && i + 1 < opts.size()) {
dir = opts[++i];
} else if (opts[i] == "--firmware") {
wantFirmware = true;
} else if (opts[i] == "--map") {
wantMap = true;
} else {
usage();
return 2;
}
}
if (!wantFirmware && !wantMap)
wantFirmware = wantMap = true;
if (dir.empty())
dir = openpu::Settings::load(openpu::paths::configDir() / "config.json").effectiveDownloadDir();
const auto type = identify(*ctx.api, vin);
if (type == openpu::HeadUnitType::Unknown)
return 1;
const openpu::AvailableUpdates updates = ctx.api->getUpdates(vin, type);
printUpdate("firmware", updates.firmware);
printUpdate("map", updates.map);
std::vector<std::pair<std::string, openpu::UpdateInfo>> jobs;
if (wantFirmware && updates.firmware)
jobs.emplace_back("firmware", *updates.firmware);
if (wantMap && updates.map)
jobs.emplace_back("map", *updates.map);
if (jobs.empty()) {
std::cout << "nothing to download\n";
return 0;
}
std::error_code ec;
fs::create_directories(dir, ec);
const auto space = fs::space(dir, ec);
std::uint64_t needed = 0;
for (const auto& j : jobs)
needed += j.second.size;
needed += needed / 10; // same 10 % margin as the official app (partial files not deducted)
if (!ec && space.available < needed)
std::cerr << "warning: " << humanSize(space.available) << " available in " << dir << ", about "
<< humanSize(needed) << " needed\n";
openpu::Downloader downloader(*ctx.transport);
for (const auto& [label, update] : jobs) {
if (!update.licenseUrl.empty()) {
const auto lic = downloader.downloadSmall(update.licenseUrl, dir, std::nullopt, &gCancel);
std::cout << "license: " << lic.file.string() << '\n';
}
const std::string name = label;
const auto result = downloader.downloadResumable(
update.url, dir,
[&name](const openpu::DownloadProgress& p) {
const auto eta = p.remaining();
std::string extra = p.resumedFrom > 0 ? "resumed " : "";
if (eta)
extra += "ETA " + duration(*eta);
if (p.attempt > 0)
extra += " retry " + std::to_string(p.attempt);
progressLine(name, p.done, p.total, extra);
},
&gCancel);
(void)std::fprintf(stderr, "\n");
std::cout << label << ": " << result.file.string() << (result.alreadyComplete ? " (already complete)" : "")
<< '\n';
}
return 0;
}
openpu::ArchiveProgressCallback archiveProgress(const std::string& label)
{
return [label](const openpu::ArchiveProgress& p) {
progressLine(label, p.processed, p.total, std::to_string(p.entries) + " entries");
};
}
int cmdVerify(const fs::path& tar)
{
openpu::verifyTar(tar, archiveProgress("verify"), &gCancel);
(void)std::fprintf(stderr, "\n");
std::cout << "ok: " << humanSize(openpu::tarPayloadSize(tar)) << " to extract\n";
return 0;
}
int cmdExtract(const fs::path& tar, const fs::path& dest)
{
openpu::extractTar(tar, dest, archiveProgress("extract"), &gCancel);
(void)std::fprintf(stderr, "\n");
std::cout << "extracted to " << dest.string() << '\n';
return 0;
}
int run(std::vector<std::string> args)
{
std::vector<std::string> args(argv + 1, argv + argc);
openpu::CurlOptions curlOptions;
if (!args.empty() && args.front() == "--verbose") {
curlOptions.verbose = true;
args.erase(args.begin());
}
if (args.size() != 2) {
if (args.size() < 2) {
usage();
return 2;
}
const std::string& command = args[0];
const std::string command = args[0];
if (command == "verify" && args.size() == 2)
return cmdVerify(args[1]);
if (command == "extract" && args.size() == 3)
return cmdExtract(args[1], args[2]);
const std::string vin = openpu::normalizeVin(args[1]);
if (!openpu::isValidVin(vin)) {
std::cerr << "error: invalid VIN (expected V[FR]3 followed by 14 letters/digits)\n";
return 2;
}
Context ctx;
ctx.transport = openpu::makeCurlTransport(curlOptions);
ctx.api = std::make_unique<openpu::ApiClient>(*ctx.transport, openpu::ApiConfig::fromEnvironment());
auto transport = openpu::makeCurlTransport(curlOptions);
openpu::ApiClient api(*transport, openpu::ApiConfig::fromEnvironment());
if (command == "check" && args.size() == 2)
return cmdCheck(ctx, vin);
if (command == "download")
return cmdDownload(ctx, vin, {args.begin() + 2, args.end()});
if (command == "raw-devices" && args.size() == 2)
return printRaw(ctx.api->rawDevices(vin));
if (command == "raw-updates" && args.size() == 2)
return printRaw(ctx.api->rawUpdates(vin, openpu::software::all()));
usage();
return 2;
}
} // namespace
int main(int argc, char** argv)
{
(void)std::signal(SIGINT, onSignal);
(void)std::signal(SIGTERM, onSignal);
try {
if (command == "raw-devices")
return printRaw(api.rawDevices(vin));
if (command == "raw-updates")
return printRaw(api.rawUpdates(vin, openpu::software::all()));
if (command != "check") {
usage();
return 2;
}
const openpu::VehicleCheck check = api.checkVehicle(vin);
if (!check.exists) {
std::cout << "vehicle not found\n";
return 1;
}
if (check.type == openpu::HeadUnitType::Unknown) {
std::cout << "vehicle found, but its head unit is not supported\n";
return 1;
}
std::cout << "head unit: " << openpu::headUnitTypeName(check.type) << "\nguide: " << check.guideKey << '\n';
const openpu::AvailableUpdates updates = api.getUpdates(vin, check.type);
printUpdate("firmware", updates.firmware);
printUpdate("map", updates.map);
return 0;
return run({argv + 1, argv + argc});
} catch (const openpu::Cancelled&) {
std::cerr << "\ncancelled\n";
return 130;
} catch (const openpu::ApiError& e) {
std::cerr << "error: " << e.what() << '\n';
return 1;
} catch (const openpu::DownloadError& e) {
std::cerr << "\ndownload error: " << e.what() << '\n';
} catch (const openpu::ArchiveError& e) {
std::cerr << "\narchive error (" << (e.kind() == openpu::ArchiveError::Kind::Corrupt ? "corrupt" : "I/O")
<< "): " << e.what() << '\n';
} catch (const openpu::StorageError& e) {
std::cerr << "error: " << e.what() << '\n';
}
return 1;
}