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

+285
View File
@@ -0,0 +1,285 @@
#include "openpu/storage.hpp"
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <nlohmann/json.hpp>
#include <sstream>
#include <system_error>
#ifdef __HAIKU__
#include <FindDirectory.h>
#include <limits.h>
#endif
namespace openpu {
namespace fs = std::filesystem;
using json = nlohmann::json;
namespace {
std::string env(const char* name)
{
const char* v = std::getenv(name); // NOLINT(concurrency-mt-unsafe)
return v != nullptr ? v : "";
}
fs::path home()
{
const std::string h = env("HOME");
return h.empty() ? fs::current_path() : fs::path(h);
}
#ifdef __HAIKU__
fs::path haikuDir(directory_which which, const fs::path& fallback)
{
char buf[PATH_MAX] = {};
if (find_directory(which, -1, false, buf, sizeof buf) == B_OK)
return buf;
return fallback;
}
#else
/// XDG_DOWNLOAD_DIR from ~/.config/user-dirs.dirs, e.g. XDG_DOWNLOAD_DIR="$HOME/Téléchargements".
fs::path xdgDownloadDir()
{
std::string cfg = env("XDG_CONFIG_HOME");
const fs::path base = cfg.empty() ? home() / ".config" : fs::path(cfg);
std::ifstream in(base / "user-dirs.dirs");
std::string line;
while (std::getline(in, line)) {
const std::string key = "XDG_DOWNLOAD_DIR=";
if (line.rfind(key, 0) != 0)
continue;
std::string v = line.substr(key.size());
if (v.size() >= 2 && v.front() == '"' && v.back() == '"')
v = v.substr(1, v.size() - 2);
const std::string var = "$HOME";
if (v.rfind(var, 0) == 0)
v = home().string() + v.substr(var.size());
if (!v.empty() && v.front() == '/')
return v;
}
return home() / "Downloads";
}
#endif
std::string readFile(const fs::path& file)
{
std::ifstream in(file, std::ios::binary);
if (!in)
throw StorageError("cannot read " + file.string());
std::stringstream ss;
ss << in.rdbuf();
return ss.str();
}
std::string str(const json& obj, const char* key)
{
auto it = obj.find(key);
return it != obj.end() && it->is_string() ? it->get<std::string>() : std::string();
}
bool boolean(const json& obj, const char* key)
{
auto it = obj.find(key);
return it != obj.end() && it->is_boolean() && it->get<bool>();
}
json parseJson(const std::string& text, const std::string& what)
{
// The official app writes UTF-8 with a BOM on Windows.
std::string_view view(text);
if (view.substr(0, 3) == "\xEF\xBB\xBF")
view.remove_prefix(3);
json doc = json::parse(view, nullptr, false);
if (doc.is_discarded() || !doc.is_object())
throw StorageError("invalid JSON in " + what);
return doc;
}
} // namespace
namespace paths {
fs::path configDir()
{
#ifdef __HAIKU__
return haikuDir(B_USER_SETTINGS_DIRECTORY, home() / "config" / "settings") / "OpenPU";
#else
const std::string xdg = env("XDG_CONFIG_HOME");
return (xdg.empty() ? home() / ".config" : fs::path(xdg)) / "openpu";
#endif
}
fs::path defaultDownloadDir()
{
#ifdef __HAIKU__
return haikuDir(B_USER_DIRECTORY, home()) / "OpenPU downloads";
#else
return xdgDownloadDir() / "OpenPU";
#endif
}
} // namespace paths
void writeFileAtomically(const fs::path& file, const std::string& content)
{
std::error_code ec;
if (file.has_parent_path())
fs::create_directories(file.parent_path(), ec);
fs::path tmp = file;
tmp += ".tmp";
{
std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
out << content;
out.flush();
if (!out)
throw StorageError("cannot write " + tmp.string());
}
fs::rename(tmp, file, ec);
if (ec) {
fs::remove(tmp, ec);
throw StorageError("cannot replace " + file.string());
}
}
// --- vehicles ---------------------------------------------------------------------------------
VehicleStore::VehicleStore(fs::path file) : file_(std::move(file)) {}
std::vector<Vehicle> VehicleStore::parse(const std::string& text)
{
const json doc = parseJson(text, "vehicles file");
std::vector<Vehicle> out;
for (const auto& [vin, v] : doc.items()) {
if (!v.is_object())
continue;
Vehicle veh;
veh.vin = vin;
veh.name = str(v, "name");
veh.type = headUnitTypeFromString(str(v, "type"));
veh.guideKey = str(v, "wave");
auto files = v.find("undeletedFiles");
if (files != v.end() && files->is_object()) {
veh.pendingFirmware = str(*files, "fw");
veh.pendingMap = str(*files, "carto");
veh.pendingLicense = str(*files, "license");
}
out.push_back(std::move(veh));
}
return out;
}
std::string VehicleStore::serialize(const std::vector<Vehicle>& vehicles)
{
json doc = json::object();
for (const auto& v : vehicles) {
json entry = {{"name", v.name}, {"type", std::string(headUnitTypeName(v.type))}, {"wave", v.guideKey}};
json files = json::object();
if (!v.pendingFirmware.empty())
files["fw"] = v.pendingFirmware;
if (!v.pendingMap.empty())
files["carto"] = v.pendingMap;
if (!v.pendingLicense.empty())
files["license"] = v.pendingLicense;
if (!files.empty())
entry["undeletedFiles"] = files;
doc[v.vin] = entry;
}
return doc.dump(2) + "\n";
}
void VehicleStore::load()
{
std::error_code ec;
if (!fs::exists(file_, ec)) {
vehicles_.clear();
return;
}
vehicles_ = parse(readFile(file_));
}
void VehicleStore::save() const
{
writeFileAtomically(file_, serialize(vehicles_));
}
const Vehicle* VehicleStore::find(const std::string& vin) const
{
auto it = std::find_if(vehicles_.begin(), vehicles_.end(), [&](const Vehicle& v) { return v.vin == vin; });
return it == vehicles_.end() ? nullptr : &*it;
}
void VehicleStore::upsert(const Vehicle& vehicle)
{
auto it = std::find_if(vehicles_.begin(), vehicles_.end(), [&](const Vehicle& v) { return v.vin == vehicle.vin; });
if (it == vehicles_.end())
vehicles_.push_back(vehicle);
else
*it = vehicle;
}
bool VehicleStore::remove(const std::string& vin)
{
const auto before = vehicles_.size();
vehicles_.erase(std::remove_if(vehicles_.begin(), vehicles_.end(), [&](const Vehicle& v) { return v.vin == vin; }),
vehicles_.end());
return vehicles_.size() != before;
}
// --- settings ---------------------------------------------------------------------------------
fs::path Settings::effectiveDownloadDir() const
{
return downloadDir.empty() ? paths::defaultDownloadDir() : downloadDir;
}
Settings Settings::load(const fs::path& file)
{
Settings s;
std::error_code ec;
if (!fs::exists(file, ec))
return s;
const json doc = parseJson(readFile(file), file.string());
s.language = str(doc, "language");
s.downloadDir = str(doc, "downloadPath");
auto p = doc.find("pendingDownload");
if (p != doc.end() && p->is_object() && !str(*p, "vin").empty()) {
PendingDownload d;
d.vin = str(*p, "vin");
d.firmware = boolean(*p, "firmware");
d.map = boolean(*p, "map");
d.firmwareVersion = str(*p, "firmwareVersion");
d.mapVersion = str(*p, "mapVersion");
d.firmwareFile = str(*p, "firmwareFile");
d.mapFile = str(*p, "mapFile");
d.licenseFile = str(*p, "licenseFile");
s.pending = d;
}
return s;
}
void Settings::save(const fs::path& file) const
{
json doc = json::object();
if (!language.empty())
doc["language"] = language;
if (!downloadDir.empty())
doc["downloadPath"] = downloadDir.string();
if (pending) {
doc["pendingDownload"] = {
{"vin", pending->vin},
{"firmware", pending->firmware},
{"map", pending->map},
{"firmwareVersion", pending->firmwareVersion},
{"mapVersion", pending->mapVersion},
{"firmwareFile", pending->firmwareFile},
{"mapFile", pending->mapFile},
{"licenseFile", pending->licenseFile},
};
}
writeFileAtomically(file, doc.dump(2) + "\n");
}
} // namespace openpu