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

+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include "openpu/cancel.hpp"
#include <cstdint>
#include <filesystem>
#include <functional>
#include <stdexcept>
#include <string>
namespace openpu {
struct ArchiveProgress {
std::uint64_t processed = 0; ///< bytes of the archive consumed so far
std::uint64_t total = 0; ///< archive size
std::uint64_t entries = 0; ///< entries seen so far
std::string current; ///< entry being processed
};
using ArchiveProgressCallback = std::function<void(const ArchiveProgress&)>;
class ArchiveError : public std::runtime_error {
public:
enum class Kind {
Corrupt, ///< the archive is damaged or not a tar: delete it and download again
Io, ///< cannot read the archive or write the destination (full / removed drive...)
};
ArchiveError(Kind kind, const std::string& what) : std::runtime_error(what), kind_(kind) {}
Kind kind() const noexcept { return kind_; }
private:
Kind kind_;
};
/// Reads every entry of a tar archive, without writing anything, to check its integrity.
void verifyTar(const std::filesystem::path& archive, const ArchiveProgressCallback& onProgress = {},
const CancelToken* cancel = nullptr);
/// Extracts a tar archive below `destination` (typically the USB stick root).
/// Entries named UpdateInfo.xml (any directory) are skipped, as in the official application.
/// Absolute paths, `..` components and links escaping the destination are refused; owners and
/// permissions are not restored (the target is FAT32).
void extractTar(const std::filesystem::path& archive, const std::filesystem::path& destination,
const ArchiveProgressCallback& onProgress = {}, const CancelToken* cancel = nullptr);
/// Sum of the uncompressed sizes of the regular files of an archive that extractTar would write.
std::uint64_t tarPayloadSize(const std::filesystem::path& archive);
} // namespace openpu
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include <atomic>
#include <stdexcept>
namespace openpu {
/// Cooperative cancellation flag shared between a UI thread and a worker.
class CancelToken {
public:
void cancel() noexcept { flag_.store(true, std::memory_order_relaxed); }
void reset() noexcept { flag_.store(false, std::memory_order_relaxed); }
bool cancelled() const noexcept { return flag_.load(std::memory_order_relaxed); }
private:
std::atomic<bool> flag_{false};
};
class Cancelled : public std::runtime_error {
public:
Cancelled() : std::runtime_error("operation cancelled") {}
};
} // namespace openpu
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include "openpu/cancel.hpp"
#include "openpu/http.hpp"
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <optional>
#include <stdexcept>
#include <string>
namespace openpu {
struct DownloadProgress {
std::uint64_t total = 0; ///< file size in bytes
std::uint64_t done = 0; ///< bytes on disk
std::uint64_t resumedFrom = 0; ///< bytes already present when this session started
std::chrono::steady_clock::duration elapsed{};
int attempt = 0; ///< 0 for the first try, then 1..maxRetries
/// Estimated remaining time based on this session's throughput (nullopt if unknown).
std::optional<std::chrono::seconds> remaining() const;
};
using ProgressCallback = std::function<void(const DownloadProgress&)>;
struct DownloadOptions {
int maxRetries = 5;
std::chrono::milliseconds connectTimeout{5000};
std::chrono::milliseconds stallTimeout{10000};
std::chrono::milliseconds retryDelay{2000};
std::chrono::milliseconds progressInterval{250};
};
class DownloadError : public std::runtime_error {
public:
enum class Kind {
Network, ///< retries exhausted
Http, ///< server refused (4xx/5xx on HEAD or GET)
Disk, ///< local write failure, fatal immediately
};
DownloadError(Kind kind, const std::string& what) : std::runtime_error(what), kind_(kind) {}
Kind kind() const noexcept { return kind_; }
private:
Kind kind_;
};
struct DownloadResult {
std::filesystem::path file;
std::uint64_t size = 0;
bool alreadyComplete = false; ///< nothing had to be transferred
};
class Downloader {
public:
explicit Downloader(Transport& transport, DownloadOptions options = {});
/// Resumable download of a (large) update archive into `dir`.
/// HEAD (following redirects) gives the size and the final URL whose last path segment is the
/// file name; an existing partial file is continued with a Range request. Network failures are
/// retried, keeping the partial file. Throws DownloadError or Cancelled.
DownloadResult downloadResumable(const std::string& url, const std::filesystem::path& dir,
const ProgressCallback& onProgress = {}, const CancelToken* cancel = nullptr);
/// Small download (license file). The name comes from Content-Disposition, falling back to the
/// URL. If `knownName` exists in `dir` it is reused without any request. The body goes to a
/// temporary file renamed on success, so an interrupted transfer never leaves a truncated file.
DownloadResult downloadSmall(const std::string& url, const std::filesystem::path& dir,
const std::optional<std::string>& knownName = std::nullopt,
const CancelToken* cancel = nullptr);
/// File name a resumable download of `url` will get (HEAD request).
std::string resolveFileName(const std::string& url);
private:
struct Probe {
std::string finalUrl;
std::uint64_t size = 0;
std::string fileName;
};
Probe probe(const std::string& url);
Transport& transport_;
DownloadOptions options_;
};
} // namespace openpu
+88
View File
@@ -0,0 +1,88 @@
#pragma once
#include "openpu/models.hpp"
#include <filesystem>
#include <optional>
#include <stdexcept>
#include <string>
#include <vector>
namespace openpu {
namespace paths {
/// Per-user settings directory: $XDG_CONFIG_HOME/openpu (Linux), ~/config/settings/OpenPU (Haiku).
std::filesystem::path configDir();
/// Default download directory: XDG download dir (or ~/Downloads) + /OpenPU; ~/OpenPU downloads on Haiku.
std::filesystem::path defaultDownloadDir();
} // namespace paths
class StorageError : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
struct Vehicle {
std::string vin;
std::string name;
HeadUnitType type = HeadUnitType::Unknown;
std::string guideKey; ///< "wave" in the official vehicles.json
/// Downloaded files not yet written to a USB stick (kept to resume or clean up later).
std::string pendingFirmware;
std::string pendingMap;
std::string pendingLicense;
};
/// vehicles.json, same layout as the official application's file: { "<VIN>": {name, type, wave, undeletedFiles} }.
class VehicleStore {
public:
explicit VehicleStore(std::filesystem::path file);
/// Loads the file; a missing file means "no vehicles". Throws StorageError on unreadable JSON.
void load();
/// Atomically rewrites the file.
void save() const;
const std::vector<Vehicle>& all() const noexcept { return vehicles_; }
const Vehicle* find(const std::string& vin) const;
void upsert(const Vehicle& vehicle);
bool remove(const std::string& vin);
/// Parses a vehicles.json document (ours or the official application's).
static std::vector<Vehicle> parse(const std::string& json);
static std::string serialize(const std::vector<Vehicle>& vehicles);
const std::filesystem::path& file() const noexcept { return file_; }
private:
std::filesystem::path file_;
std::vector<Vehicle> vehicles_;
};
/// Download in progress, persisted so that it can be resumed after a restart.
struct PendingDownload {
std::string vin;
bool firmware = false;
bool map = false;
std::string firmwareVersion;
std::string mapVersion;
std::string firmwareFile;
std::string mapFile;
std::string licenseFile;
};
struct Settings {
std::string language; ///< empty: follow the system locale
std::filesystem::path downloadDir; ///< empty: paths::defaultDownloadDir()
std::optional<PendingDownload> pending;
std::filesystem::path effectiveDownloadDir() const;
static Settings load(const std::filesystem::path& file);
void save(const std::filesystem::path& file) const;
};
/// Writes `content` to `file` through a temporary file + rename. Throws StorageError.
void writeFileAtomically(const std::filesystem::path& file, const std::string& content);
} // namespace openpu