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

+261
View File
@@ -0,0 +1,261 @@
#include "openpu/archive.hpp"
#include <archive.h>
#include <archive_entry.h>
#include <cerrno>
#include <chrono>
#include <memory>
#include <system_error>
namespace openpu {
namespace fs = std::filesystem;
namespace {
struct ReadDeleter {
void operator()(archive* a) const { archive_read_free(a); }
};
struct WriteDeleter {
void operator()(archive* a) const { archive_write_free(a); }
};
using ReadPtr = std::unique_ptr<archive, ReadDeleter>;
using WritePtr = std::unique_ptr<archive, WriteDeleter>;
constexpr std::size_t kBlockSize = 1 << 20;
std::string message(archive* a)
{
const char* m = archive_error_string(a);
return m != nullptr ? m : "unknown libarchive error";
}
/// Errors raised while *reading* the archive mean it is damaged, unless the OS reported an errno
/// (then it is an I/O problem on the source disk).
[[noreturn]] void throwReadError(archive* a, const fs::path& path)
{
const int err = archive_errno(a);
const bool io = err == EIO || err == ENOENT || err == EACCES || err == ENODEV || err == ENXIO || err == EROFS ||
err == ENOSPC;
throw ArchiveError(io ? ArchiveError::Kind::Io : ArchiveError::Kind::Corrupt,
path.filename().string() + ": " + message(a));
}
ReadPtr openTar(const fs::path& path)
{
ReadPtr a(archive_read_new());
if (!a)
throw ArchiveError(ArchiveError::Kind::Io, "archive_read_new failed");
// Only tar (ustar, pax, gnu, v7 without magic). No raw/other formats: a non-tar must fail.
archive_read_support_format_tar(a.get());
archive_read_support_filter_none(a.get());
if (archive_read_open_filename(a.get(), path.c_str(), kBlockSize) != ARCHIVE_OK) {
const int err = archive_errno(a.get());
if (err == ENOENT || err == EACCES || err == EIO)
throw ArchiveError(ArchiveError::Kind::Io, path.string() + ": " + message(a.get()));
throwReadError(a.get(), path);
}
return a;
}
std::uint64_t fileSize(const fs::path& path)
{
std::error_code ec;
const auto s = fs::file_size(path, ec);
return ec ? 0 : static_cast<std::uint64_t>(s);
}
bool isSkipped(const char* entryPath)
{
const fs::path p(entryPath != nullptr ? entryPath : "");
return p.filename() == "UpdateInfo.xml";
}
/// Normalised relative path of an entry, or empty if it is absolute or contains "..".
fs::path safeRelative(const char* entryPath)
{
if (entryPath == nullptr || *entryPath == '\0' || *entryPath == '/' || *entryPath == '\\')
return {};
fs::path out;
for (const auto& part : fs::path(entryPath)) {
const std::string s = part.string();
if (s == "..")
return {};
if (s.empty() || s == ".")
continue;
if (s.find('\\') != std::string::npos || s.find(':') != std::string::npos)
return {}; // Windows-style separators or drive letters
out /= part;
}
return out;
}
class Reporter {
public:
Reporter(archive* a, std::uint64_t total, const ArchiveProgressCallback& cb) : a_(a), cb_(cb)
{
progress_.total = total;
}
void entry(const char* name)
{
++progress_.entries;
progress_.current = name != nullptr ? name : "";
report(false);
}
void report(bool force)
{
if (!cb_)
return;
const auto now = std::chrono::steady_clock::now();
if (!force && now - last_ < std::chrono::milliseconds(250))
return;
last_ = now;
const auto pos = archive_filter_bytes(a_, -1);
progress_.processed = pos > 0 ? static_cast<std::uint64_t>(pos) : 0;
if (force)
progress_.processed = progress_.total;
cb_(progress_);
}
private:
archive* a_;
const ArchiveProgressCallback& cb_;
ArchiveProgress progress_;
std::chrono::steady_clock::time_point last_;
};
void checkCancel(const CancelToken* cancel)
{
if (cancel != nullptr && cancel->cancelled())
throw Cancelled();
}
} // namespace
void verifyTar(const fs::path& path, const ArchiveProgressCallback& onProgress, const CancelToken* cancel)
{
ReadPtr a = openTar(path);
Reporter reporter(a.get(), fileSize(path), onProgress);
archive_entry* entry = nullptr;
std::uint64_t entries = 0;
for (;;) {
checkCancel(cancel);
const int r = archive_read_next_header(a.get(), &entry);
if (r == ARCHIVE_EOF)
break;
if (r < ARCHIVE_WARN)
throwReadError(a.get(), path);
++entries;
reporter.entry(archive_entry_pathname(entry));
// Reading (not skipping) the data walks the whole file and detects truncation.
const void* buf = nullptr;
std::size_t size = 0;
la_int64_t offset = 0;
for (;;) {
const int d = archive_read_data_block(a.get(), &buf, &size, &offset);
if (d == ARCHIVE_EOF)
break;
if (d < ARCHIVE_WARN)
throwReadError(a.get(), path);
checkCancel(cancel);
reporter.report(false);
}
}
if (entries == 0)
throw ArchiveError(ArchiveError::Kind::Corrupt, path.filename().string() + ": empty archive");
reporter.report(true);
}
std::uint64_t tarPayloadSize(const fs::path& path)
{
ReadPtr a = openTar(path);
archive_entry* entry = nullptr;
std::uint64_t total = 0;
for (;;) {
const int r = archive_read_next_header(a.get(), &entry);
if (r == ARCHIVE_EOF)
break;
if (r < ARCHIVE_WARN)
throwReadError(a.get(), path);
if (archive_entry_filetype(entry) == AE_IFREG && !isSkipped(archive_entry_pathname(entry)) &&
archive_entry_size(entry) > 0)
total += static_cast<std::uint64_t>(archive_entry_size(entry));
archive_read_data_skip(a.get());
}
return total;
}
void extractTar(const fs::path& path, const fs::path& destination, const ArchiveProgressCallback& onProgress,
const CancelToken* cancel)
{
std::error_code ec;
fs::create_directories(destination, ec);
if (ec)
throw ArchiveError(ArchiveError::Kind::Io, "cannot create " + destination.string() + ": " + ec.message());
ReadPtr a = openTar(path);
WritePtr w(archive_write_disk_new());
if (!w)
throw ArchiveError(ArchiveError::Kind::Io, "archive_write_disk_new failed");
archive_write_disk_set_options(w.get(), ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_SECURE_SYMLINKS |
ARCHIVE_EXTRACT_SECURE_NODOTDOT);
Reporter reporter(a.get(), fileSize(path), onProgress);
archive_entry* entry = nullptr;
for (;;) {
checkCancel(cancel);
const int r = archive_read_next_header(a.get(), &entry);
if (r == ARCHIVE_EOF)
break;
if (r < ARCHIVE_WARN)
throwReadError(a.get(), path);
const char* name = archive_entry_pathname(entry);
reporter.entry(name);
if (isSkipped(name)) {
if (archive_read_data_skip(a.get()) < ARCHIVE_WARN)
throwReadError(a.get(), path);
continue;
}
const auto type = archive_entry_filetype(entry);
if (type != AE_IFREG && type != AE_IFDIR) {
// Links, devices, fifos cannot live on FAT32 and are never part of an update.
archive_read_data_skip(a.get());
continue;
}
// Rewrite the path below the destination, refusing anything that could escape it.
const fs::path relative = safeRelative(name);
if (relative.empty())
throw ArchiveError(ArchiveError::Kind::Corrupt,
std::string("unsafe path in archive: ") + (name != nullptr ? name : "(null)"));
const std::string target = (destination / relative).string();
archive_entry_set_pathname(entry, target.c_str());
archive_entry_set_perm(entry, type == AE_IFDIR ? 0755 : 0644);
if (archive_write_header(w.get(), entry) < ARCHIVE_WARN)
throw ArchiveError(ArchiveError::Kind::Io, std::string(name) + ": " + message(w.get()));
if (type == AE_IFREG) {
const void* buf = nullptr;
std::size_t size = 0;
la_int64_t offset = 0;
for (;;) {
const int d = archive_read_data_block(a.get(), &buf, &size, &offset);
if (d == ARCHIVE_EOF)
break;
if (d < ARCHIVE_WARN)
throwReadError(a.get(), path);
if (archive_write_data_block(w.get(), buf, size, offset) < ARCHIVE_WARN)
throw ArchiveError(ArchiveError::Kind::Io, std::string(name) + ": " + message(w.get()));
checkCancel(cancel);
reporter.report(false);
}
}
if (archive_write_finish_entry(w.get()) < ARCHIVE_WARN)
throw ArchiveError(ArchiveError::Kind::Io, std::string(name) + ": " + message(w.get()));
}
if (archive_write_close(w.get()) != ARCHIVE_OK)
throw ArchiveError(ArchiveError::Kind::Io, message(w.get()));
reporter.report(true);
}
} // namespace openpu