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:
1 parent
95704f9882
commit
543347a1e6
17 files changed
+2168
-40
No files matched your search
+10
-1
@@ -1,5 +1,6 @@
|
||||
find_package(CURL REQUIRED)
|
||||
find_package(nlohmann_json 3.2 REQUIRED)
|
||||
find_package(LibArchive REQUIRED)
|
||||
|
||||
add_library(openpu_core STATIC
|
||||
vin.cpp
|
||||
@@ -7,9 +8,17 @@ add_library(openpu_core STATIC
|
||||
http.cpp
|
||||
curl_transport.cpp
|
||||
api_client.cpp
|
||||
download.cpp
|
||||
archive.cpp
|
||||
storage.cpp
|
||||
)
|
||||
target_include_directories(openpu_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
|
||||
target_link_libraries(openpu_core
|
||||
PUBLIC CURL::libcurl
|
||||
PRIVATE nlohmann_json::nlohmann_json openpu_warnings)
|
||||
PRIVATE nlohmann_json::nlohmann_json LibArchive::LibArchive openpu_warnings)
|
||||
if(HAIKU)
|
||||
target_link_libraries(openpu_core PUBLIC be)
|
||||
endif()
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(openpu_core PUBLIC Threads::Threads)
|
||||
target_compile_definitions(openpu_core PRIVATE OPENPU_VERSION="${PROJECT_VERSION}")
|
||||
@@ -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
|
||||
@@ -0,0 +1,432 @@
|
||||
#include "openpu/download.hpp"
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
|
||||
namespace openpu {
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
std::optional<std::chrono::seconds> DownloadProgress::remaining() const
|
||||
{
|
||||
if (done >= total)
|
||||
return std::chrono::seconds(0);
|
||||
const double secs = std::chrono::duration<double>(elapsed).count();
|
||||
const std::uint64_t transferred = done > resumedFrom ? done - resumedFrom : 0;
|
||||
if (transferred == 0 || secs <= 0.0)
|
||||
return std::nullopt;
|
||||
const double rate = static_cast<double>(transferred) / secs;
|
||||
return std::chrono::seconds(static_cast<long long>(static_cast<double>(total - done) / rate));
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/// Failure worth another attempt (server hiccup, short read...), as opposed to DownloadError.
|
||||
class Retryable : public std::runtime_error {
|
||||
public:
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
|
||||
void throwIfCancelled(const CancelToken* cancel)
|
||||
{
|
||||
if (cancel != nullptr && cancel->cancelled())
|
||||
throw Cancelled();
|
||||
}
|
||||
|
||||
void interruptibleSleep(std::chrono::milliseconds total, const CancelToken* cancel)
|
||||
{
|
||||
const auto end = Clock::now() + total;
|
||||
while (Clock::now() < end) {
|
||||
throwIfCancelled(cancel);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<std::uint64_t> parseLength(const std::map<std::string, std::string>& headers)
|
||||
{
|
||||
const auto it = headers.find("content-length");
|
||||
if (it == headers.end())
|
||||
return std::nullopt;
|
||||
try {
|
||||
std::size_t pos = 0;
|
||||
const unsigned long long v = std::stoull(it->second, &pos);
|
||||
if (pos != it->second.size())
|
||||
return std::nullopt;
|
||||
return static_cast<std::uint64_t>(v);
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
/// Start offset of a `Content-Range: bytes <start>-<end>/<total>` header.
|
||||
std::optional<std::uint64_t> parseRangeStart(const std::map<std::string, std::string>& headers)
|
||||
{
|
||||
const auto it = headers.find("content-range");
|
||||
if (it == headers.end())
|
||||
return std::nullopt;
|
||||
const std::string& v = it->second;
|
||||
const auto sp = v.find(' ');
|
||||
const auto dash = v.find('-');
|
||||
if (sp == std::string::npos || dash == std::string::npos || dash < sp)
|
||||
return std::nullopt;
|
||||
try {
|
||||
return static_cast<std::uint64_t>(std::stoull(v.substr(sp + 1, dash - sp - 1)));
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
std::string errnoText()
|
||||
{
|
||||
return std::strerror(errno); // NOLINT(concurrency-mt-unsafe): message only
|
||||
}
|
||||
|
||||
/// FILE* holder whose close status is checked explicitly.
|
||||
class OutFile {
|
||||
public:
|
||||
OutFile() = default;
|
||||
OutFile(const OutFile&) = delete;
|
||||
OutFile& operator=(const OutFile&) = delete;
|
||||
~OutFile()
|
||||
{
|
||||
if (f_ != nullptr)
|
||||
(void)std::fclose(f_);
|
||||
}
|
||||
|
||||
bool open(const fs::path& path, bool append)
|
||||
{
|
||||
f_ = std::fopen(path.c_str(), append ? "ab" : "wb"); // NOLINT(cppcoreguidelines-owning-memory)
|
||||
return f_ != nullptr;
|
||||
}
|
||||
bool isOpen() const { return f_ != nullptr; }
|
||||
bool write(const char* data, std::size_t n) { return std::fwrite(data, 1, n, f_) == n; }
|
||||
bool close()
|
||||
{
|
||||
if (f_ == nullptr)
|
||||
return true;
|
||||
const bool ok = std::fclose(f_) == 0;
|
||||
f_ = nullptr;
|
||||
return ok;
|
||||
}
|
||||
|
||||
private:
|
||||
std::FILE* f_ = nullptr;
|
||||
};
|
||||
|
||||
std::uint64_t fileSizeOrZero(const fs::path& p)
|
||||
{
|
||||
std::error_code ec;
|
||||
const auto size = fs::file_size(p, ec);
|
||||
return ec ? 0 : static_cast<std::uint64_t>(size);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Downloader::Downloader(Transport& transport, DownloadOptions options) : transport_(transport), options_(options) {}
|
||||
|
||||
Downloader::Probe Downloader::probe(const std::string& url)
|
||||
{
|
||||
HttpRequest req;
|
||||
req.method = HttpMethod::Head;
|
||||
req.url = url;
|
||||
req.headers.emplace_back("Connection", "keep-alive");
|
||||
req.connectTimeout = options_.connectTimeout;
|
||||
req.stallTimeout = options_.stallTimeout;
|
||||
const HttpResponse r = transport_.perform(req);
|
||||
|
||||
if (r.status >= 400 && r.status < 500)
|
||||
throw DownloadError(DownloadError::Kind::Http, "HTTP " + std::to_string(r.status) + " for " + url);
|
||||
if (r.status != 200)
|
||||
throw Retryable("HEAD returned HTTP " + std::to_string(r.status));
|
||||
const auto length = parseLength(r.headers);
|
||||
if (!length || *length == 0)
|
||||
throw Retryable("HEAD response without Content-Length");
|
||||
|
||||
Probe p;
|
||||
p.finalUrl = r.effectiveUrl.empty() ? url : r.effectiveUrl;
|
||||
p.size = *length;
|
||||
const auto cd = r.headers.find("content-disposition");
|
||||
if (cd != r.headers.end())
|
||||
p.fileName = filenameFromContentDisposition(cd->second);
|
||||
if (p.fileName.empty())
|
||||
p.fileName = filenameFromUrl(p.finalUrl);
|
||||
if (p.fileName.empty())
|
||||
throw DownloadError(DownloadError::Kind::Http, "cannot determine a file name for " + p.finalUrl);
|
||||
return p;
|
||||
}
|
||||
|
||||
std::string Downloader::resolveFileName(const std::string& url)
|
||||
{
|
||||
for (int attempt = 0;; ++attempt) {
|
||||
try {
|
||||
return probe(url).fileName;
|
||||
} catch (const NetworkError& e) {
|
||||
if (attempt >= options_.maxRetries)
|
||||
throw DownloadError(DownloadError::Kind::Network, e.what());
|
||||
} catch (const Retryable& e) {
|
||||
if (attempt >= options_.maxRetries)
|
||||
throw DownloadError(DownloadError::Kind::Network, e.what());
|
||||
}
|
||||
std::this_thread::sleep_for(options_.retryDelay);
|
||||
}
|
||||
}
|
||||
|
||||
DownloadResult Downloader::downloadResumable(const std::string& url, const fs::path& dir,
|
||||
const ProgressCallback& onProgress, const CancelToken* cancel)
|
||||
{
|
||||
const auto start = Clock::now();
|
||||
std::optional<std::uint64_t> resumedFrom;
|
||||
bool transferredSomething = false;
|
||||
|
||||
for (int attempt = 0;; ++attempt) {
|
||||
throwIfCancelled(cancel);
|
||||
std::string failure;
|
||||
try {
|
||||
const Probe p = probe(url);
|
||||
std::error_code ec;
|
||||
fs::create_directories(dir, ec);
|
||||
if (ec)
|
||||
throw DownloadError(DownloadError::Kind::Disk, "cannot create " + dir.string() + ": " + ec.message());
|
||||
const fs::path path = dir / p.fileName;
|
||||
|
||||
std::uint64_t have = fileSizeOrZero(path);
|
||||
if (have > p.size) { // stale file from another version: start over
|
||||
fs::remove(path, ec);
|
||||
have = 0;
|
||||
}
|
||||
if (!resumedFrom)
|
||||
resumedFrom = have;
|
||||
|
||||
DownloadProgress progress;
|
||||
progress.total = p.size;
|
||||
progress.done = have;
|
||||
progress.resumedFrom = *resumedFrom;
|
||||
progress.attempt = attempt;
|
||||
auto lastReport = Clock::now() - options_.progressInterval;
|
||||
auto report = [&](bool force) {
|
||||
if (!onProgress)
|
||||
return;
|
||||
const auto now = Clock::now();
|
||||
if (!force && now - lastReport < options_.progressInterval)
|
||||
return;
|
||||
lastReport = now;
|
||||
progress.elapsed = now - start;
|
||||
onProgress(progress);
|
||||
};
|
||||
|
||||
if (have == p.size) {
|
||||
report(true);
|
||||
return {path, p.size, !transferredSomething};
|
||||
}
|
||||
|
||||
OutFile out;
|
||||
bool diskError = false;
|
||||
bool overflow = false;
|
||||
long badStatus = 0;
|
||||
std::string diskDetail;
|
||||
|
||||
HttpRequest req;
|
||||
req.method = HttpMethod::Get;
|
||||
req.url = p.finalUrl;
|
||||
req.connectTimeout = options_.connectTimeout;
|
||||
req.stallTimeout = options_.stallTimeout;
|
||||
if (have > 0)
|
||||
req.headers.emplace_back("Range", "bytes=" + std::to_string(have) + "-" + std::to_string(p.size - 1));
|
||||
|
||||
req.onHeaders = [&](long status, const std::map<std::string, std::string>& headers) {
|
||||
const auto length = parseLength(headers);
|
||||
bool append = false;
|
||||
if (status == 206 && have > 0) {
|
||||
const auto rangeStart = parseRangeStart(headers);
|
||||
if ((rangeStart && *rangeStart != have) || (length && *length != p.size - have)) {
|
||||
badStatus = status; // inconsistent partial response
|
||||
return false;
|
||||
}
|
||||
append = true;
|
||||
} else if (status == 200) {
|
||||
// No range support (or fresh download): rewrite the whole file.
|
||||
if (length && *length != p.size) {
|
||||
badStatus = status;
|
||||
return false;
|
||||
}
|
||||
progress.done = 0;
|
||||
} else {
|
||||
badStatus = status;
|
||||
return false;
|
||||
}
|
||||
if (!out.open(path, append)) {
|
||||
diskError = true;
|
||||
diskDetail = "cannot open " + path.string() + ": " + errnoText();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
req.onData = [&](const char* data, std::size_t n) {
|
||||
if (cancel != nullptr && cancel->cancelled())
|
||||
return false;
|
||||
if (progress.done + n > p.size) {
|
||||
overflow = true;
|
||||
return false;
|
||||
}
|
||||
if (!out.write(data, n)) {
|
||||
diskError = true;
|
||||
diskDetail = "write to " + path.string() + " failed: " + errnoText();
|
||||
return false;
|
||||
}
|
||||
progress.done += n;
|
||||
transferredSomething = true;
|
||||
report(false);
|
||||
return true;
|
||||
};
|
||||
|
||||
try {
|
||||
transport_.perform(req);
|
||||
} catch (const TransferAborted&) {
|
||||
(void)out.close();
|
||||
throwIfCancelled(cancel);
|
||||
if (diskError)
|
||||
throw DownloadError(DownloadError::Kind::Disk, diskDetail);
|
||||
if (overflow) {
|
||||
fs::remove(path, ec);
|
||||
throw Retryable("server sent more data than announced");
|
||||
}
|
||||
if (badStatus == 416) { // our offset is not satisfiable: restart from scratch
|
||||
fs::remove(path, ec);
|
||||
throw Retryable("HTTP 416 on range request");
|
||||
}
|
||||
if (badStatus >= 400 && badStatus < 500)
|
||||
throw DownloadError(DownloadError::Kind::Http, "HTTP " + std::to_string(badStatus) + " for " + p.finalUrl);
|
||||
throw Retryable("unexpected response (HTTP " + std::to_string(badStatus) + ")");
|
||||
} catch (const NetworkError&) {
|
||||
if (!out.close())
|
||||
throw DownloadError(DownloadError::Kind::Disk, "closing " + path.string() + ": " + errnoText());
|
||||
throw;
|
||||
}
|
||||
if (!out.close())
|
||||
throw DownloadError(DownloadError::Kind::Disk, "closing " + path.string() + ": " + errnoText());
|
||||
|
||||
report(true);
|
||||
if (fileSizeOrZero(path) != p.size)
|
||||
throw Retryable("incomplete transfer");
|
||||
return {path, p.size, false};
|
||||
} catch (const NetworkError& e) {
|
||||
failure = e.what();
|
||||
} catch (const Retryable& e) {
|
||||
failure = e.what();
|
||||
}
|
||||
if (attempt >= options_.maxRetries)
|
||||
throw DownloadError(DownloadError::Kind::Network,
|
||||
"giving up after " + std::to_string(attempt + 1) + " attempts: " + failure);
|
||||
interruptibleSleep(options_.retryDelay, cancel);
|
||||
}
|
||||
}
|
||||
|
||||
DownloadResult Downloader::downloadSmall(const std::string& url, const fs::path& dir,
|
||||
const std::optional<std::string>& knownName, const CancelToken* cancel)
|
||||
{
|
||||
std::error_code ec;
|
||||
if (knownName && !knownName->empty()) {
|
||||
const fs::path existing = dir / *knownName;
|
||||
if (fs::is_regular_file(existing, ec))
|
||||
return {existing, fileSizeOrZero(existing), true};
|
||||
}
|
||||
fs::create_directories(dir, ec);
|
||||
if (ec)
|
||||
throw DownloadError(DownloadError::Kind::Disk, "cannot create " + dir.string() + ": " + ec.message());
|
||||
|
||||
const fs::path tmp =
|
||||
dir / (".openpu-" + std::to_string(Clock::now().time_since_epoch().count()) + ".part");
|
||||
|
||||
for (int attempt = 0;; ++attempt) {
|
||||
throwIfCancelled(cancel);
|
||||
OutFile out;
|
||||
bool diskError = false;
|
||||
long badStatus = 0;
|
||||
|
||||
HttpRequest req;
|
||||
req.method = HttpMethod::Get;
|
||||
req.url = url;
|
||||
req.connectTimeout = options_.connectTimeout;
|
||||
req.stallTimeout = options_.stallTimeout;
|
||||
req.onHeaders = [&](long status, const std::map<std::string, std::string>&) {
|
||||
if (status != 200) {
|
||||
badStatus = status;
|
||||
return false;
|
||||
}
|
||||
if (!out.open(tmp, false)) {
|
||||
diskError = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
req.onData = [&](const char* data, std::size_t n) {
|
||||
if (cancel != nullptr && cancel->cancelled())
|
||||
return false;
|
||||
if (!out.write(data, n)) {
|
||||
diskError = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
std::string failure;
|
||||
try {
|
||||
const HttpResponse r = transport_.perform(req);
|
||||
if (!out.close()) {
|
||||
fs::remove(tmp, ec);
|
||||
throw DownloadError(DownloadError::Kind::Disk, "writing " + tmp.string() + ": " + errnoText());
|
||||
}
|
||||
if (fileSizeOrZero(tmp) == 0) {
|
||||
// Majestic answers the first LicenseDownload of an update with an empty
|
||||
// "licenses_<id>_<timestamp>.tar" while the license is being generated; the real
|
||||
// license_<UIN>.key comes on a later call. Never keep an empty file.
|
||||
fs::remove(tmp, ec);
|
||||
if (attempt >= options_.maxRetries)
|
||||
throw DownloadError(DownloadError::Kind::Http, "server keeps returning an empty file for " + url);
|
||||
interruptibleSleep(options_.retryDelay * (attempt + 1), cancel);
|
||||
continue;
|
||||
}
|
||||
std::string name;
|
||||
const auto cd = r.headers.find("content-disposition");
|
||||
if (cd != r.headers.end())
|
||||
name = filenameFromContentDisposition(cd->second);
|
||||
if (name.empty())
|
||||
name = filenameFromUrl(r.effectiveUrl.empty() ? url : r.effectiveUrl);
|
||||
if (name.empty() && knownName)
|
||||
name = *knownName;
|
||||
if (name.empty()) {
|
||||
fs::remove(tmp, ec);
|
||||
throw DownloadError(DownloadError::Kind::Http, "cannot determine a file name for " + url);
|
||||
}
|
||||
const fs::path finalPath = dir / name;
|
||||
fs::rename(tmp, finalPath, ec);
|
||||
if (ec) {
|
||||
fs::remove(tmp, ec);
|
||||
throw DownloadError(DownloadError::Kind::Disk, "cannot rename to " + finalPath.string());
|
||||
}
|
||||
return {finalPath, fileSizeOrZero(finalPath), false};
|
||||
} catch (const TransferAborted&) {
|
||||
(void)out.close();
|
||||
fs::remove(tmp, ec);
|
||||
throwIfCancelled(cancel);
|
||||
if (diskError)
|
||||
throw DownloadError(DownloadError::Kind::Disk, "cannot write " + tmp.string());
|
||||
if (badStatus >= 400 && badStatus < 500)
|
||||
throw DownloadError(DownloadError::Kind::Http, "HTTP " + std::to_string(badStatus) + " for " + url);
|
||||
failure = "HTTP " + std::to_string(badStatus);
|
||||
} catch (const NetworkError& e) {
|
||||
(void)out.close();
|
||||
fs::remove(tmp, ec);
|
||||
failure = e.what();
|
||||
}
|
||||
if (attempt >= options_.maxRetries)
|
||||
throw DownloadError(DownloadError::Kind::Network, "giving up: " + failure);
|
||||
interruptibleSleep(options_.retryDelay, cancel);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace openpu
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user