diff --git a/README.md b/README.md index 70fe671..a59b904 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,8 @@ C'est une alternative à l'application officielle « Peugeot Update » (Windows/ ## État - [x] Analyse de l'application existante : voir [`docs/analysis/`](docs/analysis/) - [x] Cœur C++ : VIN, API Majestic, modèles, CLI `check` -- [ ] Cœur C++ : téléchargement avec reprise, tar, USB, Job +- [x] Cœur C++ : téléchargement avec reprise, licence, tar (vérif + extraction), réglages et véhicules +- [ ] Cœur C++ : USB (UDisks2 / Haiku), orchestration (Job) - [ ] UI GTK4 (Linux) - [ ] UI Haiku - [ ] Paquets `.deb`, Flatpak et `.hpkg` @@ -31,7 +32,7 @@ src/ui-haiku interface BeAPI ## Compiler (Linux / WSL) ```sh sudo apt install build-essential cmake ninja-build pkg-config libcurl4-openssl-dev \ - libarchive-dev nlohmann-json3-dev doctest-dev + libarchive-dev nlohmann-json3-dev doctest-dev valgrind clang-tidy cppcheck cmake --preset debug && cmake --build --preset debug && ctest --preset debug ../build-openpu/debug/src/cli/openpu-cli check VF3XXXXXXXXXXXXXX tools/check.sh # tests + ASan/UBSan + valgrind + clang-tidy + cppcheck diff --git a/docs/analysis/API.md b/docs/analysis/API.md index ed276ed..3a88cb8 100644 --- a/docs/analysis/API.md +++ b/docs/analysis/API.md @@ -157,6 +157,13 @@ d'environnement standard (libcurl les gère nativement). - `installerURL` est présent au niveau racine (une URL `UpdateDownload` sur `majestic.mpsa.com`). Son rôle est inconnu et l'app d'origine ne l'utilise pas. - Un VIN inexistant renvoie **404** avec un corps HTML. +- **Licence générée de façon asynchrone** : le premier `LicenseDownload` d'une mise à jour a renvoyé un 200 + avec `Content-Disposition: filename=licenses__.tar` et un **corps vide**. + Un appel suivant renvoie le vrai `license_.key` (environ 10 Ko). L'app officielle garde le fichier vide, + d'où les ENOENT et le « redémarrer l'app » de son journal. OpenPU supprime la réponse vide et réessaie + en allongeant progressivement le délai. +- CDN firmware RCC (CloudFront) : `HEAD` → 200 + `Content-Length`, et `Range` → 206. La reprise a été vérifiée + (interruption à 1,59 Go puis reprise, environ 80 Mo/s). - Aucun en-tête particulier n'est requis : le User-Agent est libre, et HTTP/1.1 suffit (pas de négociation h2). ## 5. Mise à jour de l'application elle-même diff --git a/docs/analysis/usb-layout.md b/docs/analysis/usb-layout.md index 53283c6..7ef9da5 100644 --- a/docs/analysis/usb-layout.md +++ b/docs/analysis/usb-layout.md @@ -31,6 +31,12 @@ liste = disques USB montés dont la taille > besoin ├── rcc_update/… # contenu du tar firmware RCC (le nom dépend du calculateur) └── … # contenu du tar cartographie, extrait à la racine ``` +### Archive firmware RCC réelle (6_0432_23-2I44-1, 8 391 587 840 octets) +- Format **ustar** standard (magic `ustar\000`), 16 entrées, uniquement des fichiers réguliers et des dossiers. +- Premier membre : `UpdateInfo.xml` (racine), puis `rcc_update/…`. +- Plus gros fichiers : `rcc_update/stc.A2.bsh.tar.bin` (2,70 Go), `stc.A1…` (2,68 Go) et `rfs.A2.wml.fp.tar.bin` (1,0 Go). + Tout tient sous la limite FAT32 de 4 Gio par fichier. Pour les cartes NAC (10,5 Go), c'est à vérifier. + - Tout fichier dont le *basename* est `UpdateInfo.xml` est ignoré lors de l'extraction. - Le tar peut être sans « magic number » (`allowUnknownFormat`), donc il faut un lecteur tar tolérant (libarchive : `archive_read_support_format_tar` + `archive_read_support_format_raw` désactivé). diff --git a/src/cli/main.cpp b/src/cli/main.cpp index 5b4bc57..ca64717 100644 --- a/src/cli/main.cpp +++ b/src/cli/main.cpp @@ -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 #include +#include #include +#include #include #include namespace { +namespace fs = std::filesystem; + +openpu::CancelToken gCancel; + +extern "C" void onSignal(int /*sig*/) +{ + gCancel.cancel(); +} + void usage() { std::cerr << "usage: openpu-cli [--verbose] [args]\n" "\n" "commands:\n" - " check identify the head unit and list available updates\n" - " raw-devices print the raw devices/{VIN} response\n" - " raw-updates print the raw getAvailableUpdate response (all software types)\n" + " check identify the head unit and list available updates\n" + " download [--dir D] [--firmware] [--map]\n" + " download license + updates (both kinds by default),\n" + " resuming partial files\n" + " verify check the integrity of an update archive\n" + " extract extract an update archive (skips UpdateInfo.xml)\n" + " raw-devices print the raw devices/{VIN} response\n" + " raw-updates 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(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& 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(done) / static_cast(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 transport; + std::unique_ptr 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& 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> 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 args) { - std::vector 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(*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; } diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index eaf64c1..c724ff2 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -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}") diff --git a/src/core/archive.cpp b/src/core/archive.cpp new file mode 100644 index 0000000..5e24bb0 --- /dev/null +++ b/src/core/archive.cpp @@ -0,0 +1,261 @@ +#include "openpu/archive.hpp" + +#include +#include +#include +#include +#include +#include + +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; +using WritePtr = std::unique_ptr; + +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(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(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(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 diff --git a/src/core/download.cpp b/src/core/download.cpp new file mode 100644 index 0000000..583dde1 --- /dev/null +++ b/src/core/download.cpp @@ -0,0 +1,432 @@ +#include "openpu/download.hpp" + +#include +#include +#include +#include +#include + +namespace openpu { + +namespace fs = std::filesystem; +using Clock = std::chrono::steady_clock; + +std::optional DownloadProgress::remaining() const +{ + if (done >= total) + return std::chrono::seconds(0); + const double secs = std::chrono::duration(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(transferred) / secs; + return std::chrono::seconds(static_cast(static_cast(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 parseLength(const std::map& 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(v); + } catch (const std::exception&) { + return std::nullopt; + } +} + +/// Start offset of a `Content-Range: bytes -/` header. +std::optional parseRangeStart(const std::map& 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::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(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 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& 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& 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&) { + 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__.tar" while the license is being generated; the real + // license_.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 diff --git a/src/core/include/openpu/archive.hpp b/src/core/include/openpu/archive.hpp new file mode 100644 index 0000000..48e998d --- /dev/null +++ b/src/core/include/openpu/archive.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include "openpu/cancel.hpp" + +#include +#include +#include +#include +#include + +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; + +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 diff --git a/src/core/include/openpu/cancel.hpp b/src/core/include/openpu/cancel.hpp new file mode 100644 index 0000000..83634a4 --- /dev/null +++ b/src/core/include/openpu/cancel.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include +#include + +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 flag_{false}; +}; + +class Cancelled : public std::runtime_error { +public: + Cancelled() : std::runtime_error("operation cancelled") {} +}; + +} // namespace openpu diff --git a/src/core/include/openpu/download.hpp b/src/core/include/openpu/download.hpp new file mode 100644 index 0000000..0e2b47a --- /dev/null +++ b/src/core/include/openpu/download.hpp @@ -0,0 +1,90 @@ +#pragma once + +#include "openpu/cancel.hpp" +#include "openpu/http.hpp" + +#include +#include +#include +#include +#include +#include +#include + +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 remaining() const; +}; + +using ProgressCallback = std::function; + +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& 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 diff --git a/src/core/include/openpu/storage.hpp b/src/core/include/openpu/storage.hpp new file mode 100644 index 0000000..87ea0a4 --- /dev/null +++ b/src/core/include/openpu/storage.hpp @@ -0,0 +1,88 @@ +#pragma once + +#include "openpu/models.hpp" + +#include +#include +#include +#include +#include + +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: { "": {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& 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 parse(const std::string& json); + static std::string serialize(const std::vector& vehicles); + + const std::filesystem::path& file() const noexcept { return file_; } + +private: + std::filesystem::path file_; + std::vector 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 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 diff --git a/src/core/storage.cpp b/src/core/storage.cpp new file mode 100644 index 0000000..6c5a803 --- /dev/null +++ b/src/core/storage.cpp @@ -0,0 +1,285 @@ +#include "openpu/storage.hpp" + +#include +#include +#include +#include +#include +#include + +#ifdef __HAIKU__ +#include +#include +#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(); +} + +bool boolean(const json& obj, const char* key) +{ + auto it = obj.find(key); + return it != obj.end() && it->is_boolean() && it->get(); +} + +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 VehicleStore::parse(const std::string& text) +{ + const json doc = parseJson(text, "vehicles file"); + std::vector 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& 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 diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 3dc6628..ef47458 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -6,8 +6,12 @@ add_executable(openpu_tests test_models.cpp test_http.cpp test_api_client.cpp + test_download.cpp + test_archive.cpp + test_storage.cpp ) -target_link_libraries(openpu_tests PRIVATE openpu_core openpu_warnings) +find_package(LibArchive REQUIRED) +target_link_libraries(openpu_tests PRIVATE openpu_core openpu_warnings LibArchive::LibArchive) if(TARGET doctest::doctest) target_link_libraries(openpu_tests PRIVATE doctest::doctest) endif() diff --git a/tests/test_archive.cpp b/tests/test_archive.cpp new file mode 100644 index 0000000..123d392 --- /dev/null +++ b/tests/test_archive.cpp @@ -0,0 +1,200 @@ +#include "openpu/archive.hpp" + +#include "test_util.hpp" + +#include +#include +#include +#include +#include +#include + +using namespace openpu; +namespace fs = std::filesystem; + +namespace { + +struct Entry { + std::string path; + std::string content; + bool directory = false; + std::string symlinkTarget; +}; + +/// Writes a tar with libarchive. `format` is an ARCHIVE_FORMAT_TAR_* value. +void makeTar(const fs::path& file, const std::vector& entries, int format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED) +{ + archive* a = archive_write_new(); + archive_write_set_format(a, format); + REQUIRE(archive_write_open_filename(a, file.c_str()) == ARCHIVE_OK); + for (const auto& e : entries) { + archive_entry* entry = archive_entry_new(); + archive_entry_set_pathname(entry, e.path.c_str()); + if (e.directory) { + archive_entry_set_filetype(entry, AE_IFDIR); + archive_entry_set_perm(entry, 0755); + } else if (!e.symlinkTarget.empty()) { + archive_entry_set_filetype(entry, AE_IFLNK); + archive_entry_set_symlink(entry, e.symlinkTarget.c_str()); + } else { + archive_entry_set_filetype(entry, AE_IFREG); + archive_entry_set_perm(entry, 0600); + archive_entry_set_size(entry, static_cast(e.content.size())); + } + REQUIRE(archive_write_header(a, entry) == ARCHIVE_OK); + if (!e.content.empty()) + archive_write_data(a, e.content.data(), e.content.size()); + archive_entry_free(entry); + } + archive_write_close(a); + archive_write_free(a); +} + +std::vector rccLike() +{ + return { + {"rcc_update/", "", true, ""}, + {"rcc_update/UpdateInfo.xml", "", false, ""}, + {"rcc_update/pkg/a.bin", std::string(300000, 'x'), false, ""}, + {"rcc_update/pkg/b.txt", "hello", false, ""}, + {"./UpdateInfo.xml", "", false, ""}, + }; +} + +} // namespace + +TEST_CASE("extraction skips UpdateInfo.xml and keeps the tree") +{ + TempDir tmp; + const fs::path tar = tmp.path() / "fw.tar"; + makeTar(tar, rccLike()); + const fs::path usb = tmp.path() / "usb"; + + ArchiveProgress last; + extractTar(tar, usb, [&](const ArchiveProgress& p) { last = p; }); + CHECK(readAll(usb / "rcc_update/pkg/b.txt") == "hello"); + CHECK(fs::file_size(usb / "rcc_update/pkg/a.bin") == 300000); + CHECK_FALSE(fs::exists(usb / "rcc_update/UpdateInfo.xml")); + CHECK_FALSE(fs::exists(usb / "UpdateInfo.xml")); + CHECK(last.entries == 5); + CHECK(last.processed == last.total); +} + +TEST_CASE("payload size excludes skipped entries") +{ + TempDir tmp; + const fs::path tar = tmp.path() / "fw.tar"; + makeTar(tar, rccLike()); + CHECK(tarPayloadSize(tar) == 300000 + 5); +} + +TEST_CASE("verify accepts ustar, gnu, pax and v7 (no magic) archives") +{ + TempDir tmp; + for (int format : {ARCHIVE_FORMAT_TAR_USTAR, ARCHIVE_FORMAT_TAR_GNUTAR, ARCHIVE_FORMAT_TAR_PAX_RESTRICTED}) { + const fs::path tar = tmp.path() / ("f" + std::to_string(format) + ".tar"); + makeTar(tar, rccLike(), format); + CHECK_NOTHROW(verifyTar(tar)); + } + // V7: ustar header with the magic field blanked out (seen in some PSA archives). + const fs::path v7 = tmp.path() / "v7.tar"; + makeTar(v7, {{"file.bin", "data", false, ""}}, ARCHIVE_FORMAT_TAR_USTAR); + std::string raw = readAll(v7); + raw.replace(257, 8, std::string(8, '\0')); // magic + version + unsigned sum = 0; + raw.replace(148, 8, std::string(8, ' ')); + for (std::size_t i = 0; i < 512; ++i) + sum += static_cast(raw[i]); + char chk[8]; + std::snprintf(chk, sizeof chk, "%06o", sum); + raw.replace(148, 7, std::string(chk, 6) + '\0'); + writeAll(v7, raw); + CHECK_NOTHROW(verifyTar(v7)); + extractTar(v7, tmp.path() / "out"); + CHECK(readAll(tmp.path() / "out/file.bin") == "data"); +} + +TEST_CASE("corrupt archives are reported as Corrupt") +{ + TempDir tmp; + const fs::path tar = tmp.path() / "fw.tar"; + makeTar(tar, rccLike()); + + SUBCASE("truncated") + { + std::string raw = readAll(tar); + writeAll(tar, raw.substr(0, 100000)); + try { + verifyTar(tar); + FAIL("expected ArchiveError"); + } catch (const ArchiveError& e) { + CHECK(e.kind() == ArchiveError::Kind::Corrupt); + } + } + SUBCASE("garbage") + { + writeAll(tar, std::string(4096, '\x5a')); + try { + verifyTar(tar); + FAIL("expected ArchiveError"); + } catch (const ArchiveError& e) { + CHECK(e.kind() == ArchiveError::Kind::Corrupt); + } + } + SUBCASE("empty file") + { + writeAll(tar, ""); + CHECK_THROWS_AS(verifyTar(tar), ArchiveError); + } +} + +TEST_CASE("missing archive is an I/O error") +{ + TempDir tmp; + try { + verifyTar(tmp.path() / "nope.tar"); + FAIL("expected ArchiveError"); + } catch (const ArchiveError& e) { + CHECK(e.kind() == ArchiveError::Kind::Io); + } +} + +TEST_CASE("path traversal and links are refused") +{ + TempDir tmp; + const fs::path usb = tmp.path() / "usb"; + + SUBCASE("dot-dot") + { + const fs::path tar = tmp.path() / "evil.tar"; + makeTar(tar, {{"ok.txt", "1", false, ""}, {"../escape.txt", "x", false, ""}}); + CHECK_THROWS_AS(extractTar(tar, usb), ArchiveError); + CHECK_FALSE(fs::exists(tmp.path() / "escape.txt")); + } + SUBCASE("absolute") + { + const fs::path tar = tmp.path() / "abs.tar"; + makeTar(tar, {{(tmp.path() / "abs.txt").string(), "x", false, ""}}); + CHECK_THROWS_AS(extractTar(tar, usb), ArchiveError); + CHECK_FALSE(fs::exists(tmp.path() / "abs.txt")); + } + SUBCASE("symlinks are skipped") + { + const fs::path tar = tmp.path() / "link.tar"; + makeTar(tar, {{"link", "", false, "/etc/passwd"}, {"link2", "", false, "../.."}, {"f.txt", "ok", false, ""}}); + extractTar(tar, usb); + CHECK_FALSE(fs::exists(fs::symlink_status(usb / "link"))); + CHECK(readAll(usb / "f.txt") == "ok"); + } +} + +TEST_CASE("cancellation") +{ + TempDir tmp; + const fs::path tar = tmp.path() / "fw.tar"; + makeTar(tar, rccLike()); + CancelToken cancel; + cancel.cancel(); + CHECK_THROWS_AS(extractTar(tar, tmp.path() / "usb", {}, &cancel), Cancelled); + CHECK_THROWS_AS(verifyTar(tar, {}, &cancel), Cancelled); +} diff --git a/tests/test_download.cpp b/tests/test_download.cpp new file mode 100644 index 0000000..e098260 --- /dev/null +++ b/tests/test_download.cpp @@ -0,0 +1,344 @@ +#include "openpu/download.hpp" + +#include "test_util.hpp" + +#include +#include + +using namespace openpu; +namespace fs = std::filesystem; + +namespace { + +/// In-memory HTTP server emulating Majestic (redirect) + CDN (Range) behaviour. +class FakeCdn final : public Transport { +public: + std::string blob; + bool supportsRange = true; + /// For each of the first N GET requests, drop the connection after this many body bytes. + std::vector dropAfter; + long headStatus = 200; + long getStatus = 0; ///< forced status for GET (0 = normal behaviour) + std::string licenseBody = "LICENSE-DATA"; + std::size_t chunk = 1000; + int heads = 0; + int gets = 0; + std::vector ranges; + + static constexpr const char* entryUrl = "https://majestic.test/rest/UpdateDownload?updateId=1&uin=0"; + static constexpr const char* finalUrl = "https://cdn.test/BOSCH/RCC_EU/rcc-firmware/PSA_fw.tar?sig=abc"; + static constexpr const char* licenseUrl = "https://majestic.test/rest/LicenseDownload?mediaVersion=1&uin=0"; + + HttpResponse perform(const HttpRequest& req) override + { + HttpResponse r; + if (req.url == licenseUrl) { + r.status = 200; + r.headers["content-disposition"] = "attachment; filename=license_0000.key"; + r.effectiveUrl = req.url; + deliver(req, r, licenseBody); + return r; + } + if (req.method == HttpMethod::Head) { + ++heads; + REQUIRE(req.url == entryUrl); + r.status = headStatus; + r.effectiveUrl = finalUrl; + r.headers["content-length"] = std::to_string(blob.size()); + if (req.onHeaders) + req.onHeaders(r.status, r.headers); + return r; + } + REQUIRE(req.url == finalUrl); + const int index = gets++; + std::size_t from = 0; + std::string range; + for (const auto& [k, v] : req.headers) + if (k == "Range") + range = v; + ranges.push_back(range); + if (getStatus != 0) { + r.status = getStatus; + deliver(req, r, "error page"); + return r; + } + if (!range.empty() && supportsRange) { + from = std::stoull(range.substr(6, range.find('-') - 6)); + r.status = 206; + r.headers["content-range"] = "bytes " + std::to_string(from) + "-" + std::to_string(blob.size() - 1) + "/" + + std::to_string(blob.size()); + } else { + r.status = 200; + } + const std::string body = blob.substr(from); + r.headers["content-length"] = std::to_string(body.size()); + const std::size_t limit = + index < static_cast(dropAfter.size()) ? dropAfter[static_cast(index)] : body.size(); + deliver(req, r, body, limit); + return r; + } + +private: + void deliver(const HttpRequest& req, HttpResponse& r, const std::string& body, std::size_t limit = std::string::npos) + { + if (req.onHeaders && !req.onHeaders(r.status, r.headers)) + throw TransferAborted("aborted"); + const std::size_t end = std::min(limit, body.size()); + for (std::size_t pos = 0; pos < end; pos += chunk) { + const std::size_t n = std::min(chunk, end - pos); + if (req.onData) { + if (!req.onData(body.data() + pos, n)) + throw TransferAborted("aborted"); + } else { + r.body.append(body, pos, n); + } + } + if (end < body.size()) + throw NetworkError("connection reset"); + } +}; + +DownloadOptions fastOptions() +{ + DownloadOptions o; + o.retryDelay = std::chrono::milliseconds(0); + o.progressInterval = std::chrono::milliseconds(0); + return o; +} + +std::string makeBlob(std::size_t n) +{ + std::string s(n, '\0'); + for (std::size_t i = 0; i < n; ++i) + s[i] = static_cast('a' + (i * 7) % 26); + return s; +} + +} // namespace + +TEST_CASE("fresh download follows the redirect and names the file after the final URL") +{ + TempDir dir; + FakeCdn cdn; + cdn.blob = makeBlob(10000); + Downloader dl(cdn, fastOptions()); + + std::vector seen; + const auto r = dl.downloadResumable(FakeCdn::entryUrl, dir.path(), [&](const DownloadProgress& p) { seen.push_back(p); }); + CHECK(r.file == dir.path() / "PSA_fw.tar"); + CHECK(r.size == 10000); + CHECK_FALSE(r.alreadyComplete); + CHECK(readAll(r.file) == cdn.blob); + CHECK(cdn.ranges.front().empty()); // no Range header for a fresh file + REQUIRE_FALSE(seen.empty()); + CHECK(seen.back().done == 10000); + CHECK(seen.back().total == 10000); +} + +TEST_CASE("interrupted download is resumed with a Range request") +{ + TempDir dir; + FakeCdn cdn; + cdn.blob = makeBlob(10000); + cdn.dropAfter = {3000, 2000}; + Downloader dl(cdn, fastOptions()); + + const auto r = dl.downloadResumable(FakeCdn::entryUrl, dir.path()); + CHECK(readAll(r.file) == cdn.blob); + REQUIRE(cdn.gets == 3); + CHECK(cdn.ranges[0].empty()); + CHECK(cdn.ranges[1] == "bytes=3000-9999"); + CHECK(cdn.ranges[2] == "bytes=5000-9999"); + CHECK(cdn.heads == 3); // re-probed each attempt (signed CDN URLs may expire) +} + +TEST_CASE("existing partial file from a previous session is continued") +{ + TempDir dir; + FakeCdn cdn; + cdn.blob = makeBlob(5000); + writeAll(dir.path() / "PSA_fw.tar", cdn.blob.substr(0, 1234)); + Downloader dl(cdn, fastOptions()); + + DownloadProgress last; + dl.downloadResumable(FakeCdn::entryUrl, dir.path(), [&](const DownloadProgress& p) { last = p; }); + CHECK(readAll(dir.path() / "PSA_fw.tar") == cdn.blob); + CHECK(cdn.ranges[0] == "bytes=1234-4999"); + CHECK(last.resumedFrom == 1234); +} + +TEST_CASE("complete file is not downloaded again") +{ + TempDir dir; + FakeCdn cdn; + cdn.blob = makeBlob(100); + writeAll(dir.path() / "PSA_fw.tar", cdn.blob); + Downloader dl(cdn, fastOptions()); + const auto r = dl.downloadResumable(FakeCdn::entryUrl, dir.path()); + CHECK(r.alreadyComplete); + CHECK(cdn.gets == 0); +} + +TEST_CASE("server without Range support: file rewritten from the start") +{ + TempDir dir; + FakeCdn cdn; + cdn.blob = makeBlob(4000); + cdn.supportsRange = false; + writeAll(dir.path() / "PSA_fw.tar", std::string(1500, 'Z')); // garbage partial + Downloader dl(cdn, fastOptions()); + dl.downloadResumable(FakeCdn::entryUrl, dir.path()); + CHECK(readAll(dir.path() / "PSA_fw.tar") == cdn.blob); +} + +TEST_CASE("larger local file than announced is discarded") +{ + TempDir dir; + FakeCdn cdn; + cdn.blob = makeBlob(100); + writeAll(dir.path() / "PSA_fw.tar", std::string(500, 'Z')); + Downloader dl(cdn, fastOptions()); + dl.downloadResumable(FakeCdn::entryUrl, dir.path()); + CHECK(readAll(dir.path() / "PSA_fw.tar") == cdn.blob); +} + +TEST_CASE("retries are bounded and the partial file is kept") +{ + TempDir dir; + FakeCdn cdn; + cdn.blob = makeBlob(10000); + cdn.dropAfter = std::vector(10, 1000); // never completes... but makes progress + auto o = fastOptions(); + o.maxRetries = 2; + Downloader dl(cdn, o); + try { + dl.downloadResumable(FakeCdn::entryUrl, dir.path()); + FAIL("expected DownloadError"); + } catch (const DownloadError& e) { + CHECK(e.kind() == DownloadError::Kind::Network); + } + CHECK(cdn.gets == 3); + CHECK(fs::file_size(dir.path() / "PSA_fw.tar") == 3000); +} + +TEST_CASE("HTTP 4xx is fatal, no retry") +{ + TempDir dir; + FakeCdn cdn; + cdn.blob = makeBlob(10); + cdn.headStatus = 403; + Downloader dl(cdn, fastOptions()); + try { + dl.downloadResumable(FakeCdn::entryUrl, dir.path()); + FAIL("expected DownloadError"); + } catch (const DownloadError& e) { + CHECK(e.kind() == DownloadError::Kind::Http); + } + CHECK(cdn.heads == 1); +} + +TEST_CASE("cancellation stops the transfer and keeps the partial file") +{ + TempDir dir; + FakeCdn cdn; + cdn.blob = makeBlob(10000); + Downloader dl(cdn, fastOptions()); + CancelToken cancel; + CHECK_THROWS_AS(dl.downloadResumable( + FakeCdn::entryUrl, dir.path(), + [&](const DownloadProgress& p) { + if (p.done >= 4000) + cancel.cancel(); + }, + &cancel), + Cancelled); + const auto size = fs::file_size(dir.path() / "PSA_fw.tar"); + CHECK(size >= 4000); + CHECK(size < 10000); +} + +TEST_CASE("small download uses Content-Disposition and a temporary file") +{ + TempDir dir; + FakeCdn cdn; + Downloader dl(cdn, fastOptions()); + const auto r = dl.downloadSmall(FakeCdn::licenseUrl, dir.path()); + CHECK(r.file == dir.path() / "license_0000.key"); + CHECK(readAll(r.file) == "LICENSE-DATA"); + std::size_t count = 0; + for ([[maybe_unused]] const auto& e : fs::directory_iterator(dir.path())) + ++count; + CHECK(count == 1); // no leftover .part + + SUBCASE("known existing file is reused without request") + { + cdn.licenseBody = "CHANGED"; + const auto again = dl.downloadSmall(FakeCdn::licenseUrl, dir.path(), std::string("license_0000.key")); + CHECK(again.alreadyComplete); + CHECK(readAll(again.file) == "LICENSE-DATA"); + } +} + +namespace { + +/// LicenseDownload that first answers with an empty placeholder, like the real backend. +class LazyLicense final : public Transport { +public: + int calls = 0; + int emptyAnswers = 1; + HttpResponse perform(const HttpRequest& req) override + { + ++calls; + HttpResponse r; + r.status = 200; + const bool empty = calls <= emptyAnswers; + r.headers["content-disposition"] = + empty ? "attachment; filename=licenses_1_20261128185520.tar" : "attachment; filename=license_ABC.key"; + if (req.onHeaders && !req.onHeaders(r.status, r.headers)) + throw TransferAborted("aborted"); + if (!empty) { + const std::string body = "KEY"; + if (req.onData && !req.onData(body.data(), body.size())) + throw TransferAborted("aborted"); + } + return r; + } +}; + +} // namespace + +TEST_CASE("empty license placeholder is discarded and the request repeated") +{ + TempDir dir; + LazyLicense server; + Downloader dl(server, fastOptions()); + const auto r = dl.downloadSmall("https://majestic.test/rest/LicenseDownload?x", dir.path()); + CHECK(server.calls == 2); + CHECK(r.file.filename() == "license_ABC.key"); + CHECK(readAll(r.file) == "KEY"); + CHECK_FALSE(fs::exists(dir.path() / "licenses_1_20261128185520.tar")); + + SUBCASE("gives up when it never arrives") + { + LazyLicense never; + never.emptyAnswers = 100; + auto o = fastOptions(); + o.maxRetries = 3; + Downloader dl2(never, o); + CHECK_THROWS_AS(dl2.downloadSmall("https://majestic.test/rest/LicenseDownload?x", dir.path()), DownloadError); + CHECK(never.calls == 4); + } +} + +TEST_CASE("remaining time estimate") +{ + DownloadProgress p; + p.total = 1000; + p.resumedFrom = 200; + p.done = 600; + p.elapsed = std::chrono::seconds(4); // 400 bytes in 4 s -> 100 B/s, 400 left + REQUIRE(p.remaining().has_value()); + CHECK(p.remaining()->count() == 4); + p.done = 200; + CHECK_FALSE(p.remaining().has_value()); +} diff --git a/tests/test_storage.cpp b/tests/test_storage.cpp new file mode 100644 index 0000000..6ba2890 --- /dev/null +++ b/tests/test_storage.cpp @@ -0,0 +1,106 @@ +#include "openpu/storage.hpp" + +#include "test_util.hpp" + +#include + +using namespace openpu; + +TEST_CASE("official vehicles.json (with BOM) is understood") +{ + const std::string official = "\xEF\xBB\xBF" + R"({"VF3AAAAAAAAAAAAA1":{"name":"5008","type":"nac","wave":"path_guide_wave_4"},)" + R"("VR3AAAAAAAAAAAAA2":{"name":"e208","type":"rcc","wave":"path_guide_rcc",)" + R"("undeletedFiles":{"fw":"C:\\dl\\PSA_rcc.tar","license":"C:\\dl\\license_X.key"}}})"; + const auto v = VehicleStore::parse(official); + REQUIRE(v.size() == 2); + CHECK(v[0].vin == "VF3AAAAAAAAAAAAA1"); + CHECK(v[0].type == HeadUnitType::Nac); + CHECK(v[0].guideKey == "path_guide_wave_4"); + CHECK(v[1].type == HeadUnitType::Rcc); + CHECK(v[1].pendingFirmware == "C:\\dl\\PSA_rcc.tar"); + CHECK(v[1].pendingLicense == "C:\\dl\\license_X.key"); + CHECK(v[1].pendingMap.empty()); +} + +TEST_CASE("vehicle store round trip") +{ + TempDir tmp; + VehicleStore store(tmp.path() / "sub" / "vehicles.json"); + store.load(); // missing file + CHECK(store.all().empty()); + + Vehicle a; + a.vin = "VF3AAAAAAAAAAAAA1"; + a.name = "Ma 208"; + a.type = HeadUnitType::Nac; + a.guideKey = "path_guide_wave_2"; + store.upsert(a); + Vehicle b = a; + b.vin = "VR3AAAAAAAAAAAAA2"; + b.type = HeadUnitType::CronyNonav; + b.pendingMap = "/dl/map.tar"; + store.upsert(b); + a.name = "renamed"; + store.upsert(a); + store.save(); + + VehicleStore again(store.file()); + again.load(); + REQUIRE(again.all().size() == 2); + REQUIRE(again.find("VF3AAAAAAAAAAAAA1") != nullptr); + CHECK(again.find("VF3AAAAAAAAAAAAA1")->name == "renamed"); + CHECK(again.find("VR3AAAAAAAAAAAAA2")->type == HeadUnitType::CronyNonav); + CHECK(again.find("VR3AAAAAAAAAAAAA2")->pendingMap == "/dl/map.tar"); + CHECK(again.remove("VF3AAAAAAAAAAAAA1")); + CHECK_FALSE(again.remove("VF3AAAAAAAAAAAAA1")); + CHECK(again.all().size() == 1); +} + +TEST_CASE("corrupt vehicles file is an error, not silently emptied") +{ + TempDir tmp; + writeAll(tmp.path() / "vehicles.json", "{broken"); + VehicleStore store(tmp.path() / "vehicles.json"); + CHECK_THROWS_AS(store.load(), StorageError); +} + +TEST_CASE("settings round trip") +{ + TempDir tmp; + const auto file = tmp.path() / "config.json"; + Settings s = Settings::load(file); + CHECK(s.language.empty()); + CHECK_FALSE(s.pending.has_value()); + CHECK_FALSE(s.effectiveDownloadDir().empty()); + + s.language = "fr"; + s.downloadDir = "/data/dl"; + PendingDownload p; + p.vin = "VR3AAAAAAAAAAAAA2"; + p.firmware = true; + p.firmwareFile = "PSA_rcc.tar"; + p.licenseFile = "license_X.key"; + s.pending = p; + s.save(file); + + const Settings r = Settings::load(file); + CHECK(r.language == "fr"); + CHECK(r.effectiveDownloadDir() == "/data/dl"); + REQUIRE(r.pending.has_value()); + CHECK(r.pending->firmware); + CHECK_FALSE(r.pending->map); + CHECK(r.pending->licenseFile == "license_X.key"); +} + +TEST_CASE("XDG paths") +{ + // Only checks the shape: paths end with our application directory. +#ifdef __HAIKU__ + CHECK(paths::configDir().filename() == "OpenPU"); + CHECK(paths::defaultDownloadDir().filename() == "OpenPU downloads"); +#else + CHECK(paths::configDir().filename() == "openpu"); + CHECK(paths::defaultDownloadDir().filename() == "OpenPU"); +#endif +} diff --git a/tests/test_util.hpp b/tests/test_util.hpp new file mode 100644 index 0000000..dbb6885 --- /dev/null +++ b/tests/test_util.hpp @@ -0,0 +1,47 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +/// Self-deleting temporary directory. +class TempDir { +public: + TempDir() + { + static std::atomic counter{0}; + path_ = std::filesystem::temp_directory_path() / + ("openpu-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + "-" + + std::to_string(counter++)); + std::filesystem::create_directories(path_); + } + TempDir(const TempDir&) = delete; + TempDir& operator=(const TempDir&) = delete; + ~TempDir() + { + std::error_code ec; + std::filesystem::remove_all(path_, ec); + } + const std::filesystem::path& path() const { return path_; } + +private: + std::filesystem::path path_; +}; + +inline std::string readAll(const std::filesystem::path& p) +{ + std::ifstream in(p, std::ios::binary); + std::stringstream ss; + ss << in.rdbuf(); + return ss.str(); +} + +inline void writeAll(const std::filesystem::path& p, const std::string& content) +{ + std::filesystem::create_directories(p.parent_path()); + std::ofstream out(p, std::ios::binary | std::ios::trunc); + out << content; +}