diff --git a/README.md b/README.md index a59b904..eb0a17b 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,8 @@ C'est une alternative à l'application officielle « Peugeot Update » (Windows/ - [x] Analyse de l'application existante : voir [`docs/analysis/`](docs/analysis/) - [x] Cœur C++ : VIN, API Majestic, modèles, CLI `check` - [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) +- [x] USB Linux (UDisks2 : liste, MBR + FAT32, montage, éjection) + écriture de la mise à jour +- [ ] USB Haiku (Storage Kit) - [ ] UI GTK4 (Linux) - [ ] UI Haiku - [ ] Paquets `.deb`, Flatpak et `.hpkg` @@ -32,8 +33,12 @@ 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 valgrind clang-tidy cppcheck + libarchive-dev nlohmann-json3-dev doctest-dev libglib2.0-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 + +# test USB de bout en bout sur une image loop (paquets udisks2 dosfstools mtools) +sudo tools/dev-polkit.sh install # WSL/CI uniquement : polkit sans agent +tools/e2e-usb.sh ../build-openpu/debug/src/cli/openpu-cli --license X.key update.tar ``` diff --git a/src/cli/main.cpp b/src/cli/main.cpp index ca64717..0dd9c22 100644 --- a/src/cli/main.cpp +++ b/src/cli/main.cpp @@ -4,8 +4,10 @@ #include "openpu/archive.hpp" #include "openpu/download.hpp" #include "openpu/storage.hpp" +#include "openpu/usb.hpp" #include "openpu/vin.hpp" +#include #include #include #include @@ -36,6 +38,11 @@ void usage() " resuming partial files\n" " verify check the integrity of an update archive\n" " extract extract an update archive (skips UpdateInfo.xml)\n" + " usb-list list removable USB drives\n" + " write-usb [--license F] [--label L] [--yes] [--no-eject] ...\n" + " ERASE , format FAT32 and write the update\n" + " write-dir [--license F] ...\n" + " write the update into an existing directory\n" " raw-devices print the raw devices/{VIN} response\n" " raw-updates print the raw getAvailableUpdate response\n" "\n" @@ -221,6 +228,132 @@ int cmdExtract(const fs::path& tar, const fs::path& dest) return 0; } +const char* stepName(openpu::UsbStep s) +{ + switch (s) { + case openpu::UsbStep::Verifying: return "verify "; + case openpu::UsbStep::Formatting: return "format "; + case openpu::UsbStep::CopyingLicense: return "license"; + case openpu::UsbStep::Extracting: return "write "; + case openpu::UsbStep::Ejecting: return "eject "; + case openpu::UsbStep::Done: return "done "; + } + return ""; +} + +openpu::UsbProgressCallback usbProgress() +{ + return [last = openpu::UsbStep::Done](const openpu::UsbProgress& p) mutable { + if (p.step != last && last != openpu::UsbStep::Done) + (void)std::fprintf(stderr, "\n"); + last = p.step; + std::string label = stepName(p.step); + if (p.archiveCount > 1 && (p.step == openpu::UsbStep::Verifying || p.step == openpu::UsbStep::Extracting)) + label += " " + std::to_string(p.archiveIndex + 1) + "/" + std::to_string(p.archiveCount); + if (p.total > 0) + progressLine(label, p.done, p.total, ""); + else + (void)std::fprintf(stderr, "\r%s %s ", label.c_str(), p.detail.c_str()); + }; +} + +/// Parses "[--license F] [--label L] [--yes] [--no-eject] archives..." options. +struct WriteOptions { + openpu::UsbWritePlan plan; + std::string label; + bool yes = false; + bool eject = true; + bool ok = true; +}; + +WriteOptions parseWriteOptions(const std::vector& opts) +{ + WriteOptions w; + for (std::size_t i = 0; i < opts.size(); ++i) { + if (opts[i] == "--license" && i + 1 < opts.size()) + w.plan.license = fs::path(opts[++i]); + else if (opts[i] == "--label" && i + 1 < opts.size()) + w.label = opts[++i]; + else if (opts[i] == "--yes") + w.yes = true; + else if (opts[i] == "--no-eject") + w.eject = false; + else if (opts[i].rfind("--", 0) == 0) + w.ok = false; + else + w.plan.archives.emplace_back(opts[i]); + } + if (w.plan.archives.empty() && !w.plan.license) + w.ok = false; + return w; +} + +int cmdUsbList() +{ + auto backend = openpu::makeUsbBackend(); + const auto drives = backend->list(); + if (drives.empty()) + std::cout << "no removable USB drive found\n"; + for (const auto& d : drives) { + std::cout << d.device << " " << d.description() << (d.label.empty() ? "" : " label=" + d.label); + for (const auto& mp : d.mountPoints) + std::cout << " mounted=" << mp.string(); + std::cout << '\n'; + } + return 0; +} + +int cmdWriteUsb(const std::string& target, const std::vector& opts) +{ + WriteOptions w = parseWriteOptions(opts); + if (!w.ok) { + usage(); + return 2; + } + auto backend = openpu::makeUsbBackend(); + const auto drives = backend->list(); + const auto it = std::find_if(drives.begin(), drives.end(), + [&](const openpu::UsbDrive& d) { return d.device == target || d.id == target; }); + if (it == drives.end()) { + std::cerr << "error: " << target << " is not a removable USB drive (see usb-list)\n"; + return 1; + } + const std::uint64_t payload = w.plan.payloadSize(); + if (it->size < openpu::withMargin(payload)) { + std::cerr << "error: " << it->description() << " is too small: " << humanSize(openpu::withMargin(payload)) + << " needed (a " << humanSize(openpu::minimumStickSize(payload)) << " stick)\n"; + return 1; + } + const std::string label = openpu::sanitizeLabel(w.label.empty() ? it->label : w.label); + if (!w.yes) { + std::cout << "ALL DATA ON " << it->description() << " WILL BE ERASED.\n" + << "It will be formatted FAT32 with label " << label << ". Type YES to continue: " << std::flush; + std::string answer; + std::getline(std::cin, answer); + if (answer != "YES") { + std::cout << "aborted\n"; + return 1; + } + } + openpu::writeToUsb(*backend, *it, label, w.plan, usbProgress(), &gCancel, w.eject); + (void)std::fprintf(stderr, "\n"); + std::cout << "the USB stick is ready" << (w.eject ? " and can be removed" : "") << '\n'; + return 0; +} + +int cmdWriteDir(const fs::path& dir, const std::vector& opts) +{ + WriteOptions w = parseWriteOptions(opts); + if (!w.ok) { + usage(); + return 2; + } + openpu::writePayload(dir, w.plan, usbProgress(), &gCancel); + (void)std::fprintf(stderr, "\n"); + std::cout << "written to " << dir.string() << '\n'; + return 0; +} + int run(std::vector args) { openpu::CurlOptions curlOptions; @@ -228,11 +361,17 @@ int run(std::vector args) curlOptions.verbose = true; args.erase(args.begin()); } + if (args.size() == 1 && args[0] == "usb-list") + return cmdUsbList(); if (args.size() < 2) { usage(); return 2; } const std::string command = args[0]; + if (command == "write-usb") + return cmdWriteUsb(args[1], {args.begin() + 2, args.end()}); + if (command == "write-dir") + return cmdWriteDir(args[1], {args.begin() + 2, args.end()}); if (command == "verify" && args.size() == 2) return cmdVerify(args[1]); if (command == "extract" && args.size() == 3) @@ -277,6 +416,8 @@ int main(int argc, char** argv) } catch (const openpu::ArchiveError& e) { std::cerr << "\narchive error (" << (e.kind() == openpu::ArchiveError::Kind::Corrupt ? "corrupt" : "I/O") << "): " << e.what() << '\n'; + } catch (const openpu::UsbError& e) { + std::cerr << "\nUSB error: " << e.what() << '\n'; } catch (const openpu::StorageError& e) { std::cerr << "error: " << e.what() << '\n'; } diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index c724ff2..35688d0 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -1,6 +1,7 @@ find_package(CURL REQUIRED) find_package(nlohmann_json 3.2 REQUIRED) find_package(LibArchive REQUIRED) +find_package(Threads REQUIRED) add_library(openpu_core STATIC vin.cpp @@ -11,14 +12,23 @@ add_library(openpu_core STATIC download.cpp archive.cpp storage.cpp + usb.cpp ) target_include_directories(openpu_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_link_libraries(openpu_core - PUBLIC CURL::libcurl + PUBLIC CURL::libcurl Threads::Threads 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}") + +# USB backend +if(HAIKU) + target_sources(openpu_core PRIVATE usb_haiku.cpp) + target_link_libraries(openpu_core PUBLIC be) +elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") + find_package(PkgConfig REQUIRED) + pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + target_sources(openpu_core PRIVATE usb_udisks.cpp) + target_link_libraries(openpu_core PRIVATE PkgConfig::GIO) +else() + target_sources(openpu_core PRIVATE usb_none.cpp) +endif() diff --git a/src/core/include/openpu/usb.hpp b/src/core/include/openpu/usb.hpp new file mode 100644 index 0000000..835493a --- /dev/null +++ b/src/core/include/openpu/usb.hpp @@ -0,0 +1,102 @@ +#pragma once + +#include "openpu/cancel.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace openpu { + +/// A removable disk that can receive an update. +struct UsbDrive { + std::string id; ///< backend identifier (UDisks2 block object path, Haiku device path) + std::string device; ///< user-facing device node, e.g. /dev/sdb + std::string vendor; + std::string model; + std::string label; ///< current volume label (first partition), may be empty + std::uint64_t size = 0; ///< bytes + std::vector mountPoints; + bool isLoop = false; ///< loop device exposed for testing (OPENPU_USB_ALLOW_LOOP=1) + + /// "SanDisk Ultra (/dev/sdb, 32.0 GB)"-style description. + std::string description() const; +}; + +class UsbError : public std::runtime_error { +public: + enum class Kind { + Unavailable, ///< no backend (UDisks2 not running...) + NotAuthorized,///< polkit / permission refused + Busy, ///< cannot unmount + Failed, ///< any other backend failure + }; + UsbError(Kind kind, const std::string& what) : std::runtime_error(what), kind_(kind) {} + Kind kind() const noexcept { return kind_; } + +private: + Kind kind_; +}; + +class UsbBackend { +public: + virtual ~UsbBackend() = default; + /// Removable USB disks (whole devices, never system disks). + virtual std::vector list() = 0; + /// Erases the drive: new MBR table with a single FAT32 partition named `label`, then mounts it. + /// Returns the mount point of the new file system. + virtual std::filesystem::path formatFat32(const UsbDrive& drive, const std::string& label) = 0; + /// Flushes, unmounts and powers off / ejects the drive. + virtual void eject(const UsbDrive& drive) = 0; +}; + +/// UDisks2 on Linux, Storage Kit on Haiku. Throws UsbError(Unavailable) if none can be used. +std::unique_ptr makeUsbBackend(); + +/// Volume label rules of the official app: keep [A-Za-z0-9_], max 11 chars, upper case, default "NEW". +std::string sanitizeLabel(std::string_view label); + +/// Smallest stick size (2, 4, 8... GB, decimal) able to hold `bytes` (+10 % margin, as the official app). +std::uint64_t minimumStickSize(std::uint64_t bytes); +/// Required free size for `bytes` of payload (+10 %). +std::uint64_t withMargin(std::uint64_t bytes); + +// --- writing an update ----------------------------------------------------------------------- + +enum class UsbStep { Verifying, Formatting, CopyingLicense, Extracting, Ejecting, Done }; + +struct UsbProgress { + UsbStep step = UsbStep::Verifying; + std::size_t archiveIndex = 0; ///< archive being verified / extracted + std::size_t archiveCount = 0; + std::uint64_t done = 0; ///< bytes of the current archive + std::uint64_t total = 0; + std::string detail; ///< current entry +}; +using UsbProgressCallback = std::function; + +struct UsbWritePlan { + std::optional license; ///< copied to /license/ + std::vector archives; ///< extracted in order (firmware, then map) + + /// Bytes written on the stick (license + archive payloads). + std::uint64_t payloadSize() const; +}; + +/// Copies the license and extracts the archives below `root` (no formatting). Used by +/// writeToUsb and to prepare an already formatted / mounted stick or a test directory. +void writePayload(const std::filesystem::path& root, const UsbWritePlan& plan, const UsbProgressCallback& onProgress = {}, + const CancelToken* cancel = nullptr); + +/// Full sequence of the official application: verify archives, format FAT32, copy the license, +/// extract the archives, eject. Throws ArchiveError, UsbError, Cancelled. +void writeToUsb(UsbBackend& backend, const UsbDrive& drive, const std::string& label, const UsbWritePlan& plan, + const UsbProgressCallback& onProgress = {}, const CancelToken* cancel = nullptr, bool eject = true); + +} // namespace openpu diff --git a/src/core/usb.cpp b/src/core/usb.cpp new file mode 100644 index 0000000..8b4b3f2 --- /dev/null +++ b/src/core/usb.cpp @@ -0,0 +1,153 @@ +#include "openpu/usb.hpp" + +#include "openpu/archive.hpp" + +#include +#include +#include + +namespace openpu { + +namespace fs = std::filesystem; + +std::string UsbDrive::description() const +{ + std::string name = vendor; + if (!model.empty()) + name += (name.empty() ? "" : " ") + model; + if (name.empty()) + name = label.empty() ? "USB drive" : label; + char size_text[32]; + (void)std::snprintf(size_text, sizeof size_text, "%.1f GB", static_cast(size) / 1e9); + return name + " (" + device + ", " + size_text + ")"; +} + +std::string sanitizeLabel(std::string_view label) +{ + std::string out; + for (char c : label) { + const auto uc = static_cast(c); + if (std::isalnum(uc) != 0 || c == '_') { + out.push_back(static_cast(std::toupper(uc))); + if (out.size() == 11) + break; + } + } + return out.empty() ? "NEW" : out; +} + +std::uint64_t withMargin(std::uint64_t bytes) +{ + return bytes + bytes / 10; +} + +std::uint64_t minimumStickSize(std::uint64_t bytes) +{ + const std::uint64_t needed = withMargin(bytes); + std::uint64_t gb = 2; + while (gb * 1000000000ULL < needed) + gb *= 2; + return gb * 1000000000ULL; +} + +std::uint64_t UsbWritePlan::payloadSize() const +{ + std::uint64_t total = 0; + std::error_code ec; + if (license) { + const auto s = fs::file_size(*license, ec); + if (!ec) + total += s; + } + for (const auto& a : archives) + total += tarPayloadSize(a); + return total; +} + +namespace { + +void notify(const UsbProgressCallback& cb, const UsbProgress& p) +{ + if (cb) + cb(p); +} + +} // namespace + +void writePayload(const fs::path& root, const UsbWritePlan& plan, const UsbProgressCallback& onProgress, + const CancelToken* cancel) +{ + UsbProgress p; + p.archiveCount = plan.archives.size(); + if (plan.license) { + p.step = UsbStep::CopyingLicense; + p.detail = plan.license->filename().string(); + notify(onProgress, p); + std::error_code ec; + const fs::path dir = root / "license"; + fs::create_directories(dir, ec); + if (!ec) + fs::copy_file(*plan.license, dir / plan.license->filename(), fs::copy_options::overwrite_existing, ec); + if (ec) + throw ArchiveError(ArchiveError::Kind::Io, "cannot copy the license to " + dir.string() + ": " + ec.message()); + } + for (std::size_t i = 0; i < plan.archives.size(); ++i) { + if (cancel != nullptr && cancel->cancelled()) + throw Cancelled(); + p.step = UsbStep::Extracting; + p.archiveIndex = i; + extractTar(plan.archives[i], root, + [&](const ArchiveProgress& ap) { + p.done = ap.processed; + p.total = ap.total; + p.detail = ap.current; + notify(onProgress, p); + }, + cancel); + } +} + +void writeToUsb(UsbBackend& backend, const UsbDrive& drive, const std::string& label, const UsbWritePlan& plan, + const UsbProgressCallback& onProgress, const CancelToken* cancel, bool eject) +{ + UsbProgress p; + p.archiveCount = plan.archives.size(); + + // 1. Integrity of every archive *before* erasing anything. + for (std::size_t i = 0; i < plan.archives.size(); ++i) { + p.step = UsbStep::Verifying; + p.archiveIndex = i; + verifyTar(plan.archives[i], + [&](const ArchiveProgress& ap) { + p.done = ap.processed; + p.total = ap.total; + p.detail = ap.current; + notify(onProgress, p); + }, + cancel); + } + if (cancel != nullptr && cancel->cancelled()) + throw Cancelled(); + + // 2. Format. Past this point the stick content is gone anyway. + p = UsbProgress{}; + p.step = UsbStep::Formatting; + p.archiveCount = plan.archives.size(); + notify(onProgress, p); + const fs::path root = backend.formatFat32(drive, sanitizeLabel(label)); + + // 3-4. License + archives. + writePayload(root, plan, onProgress, cancel); + + // 5. Eject (flushes the FAT). + if (eject) { + p = UsbProgress{}; + p.step = UsbStep::Ejecting; + notify(onProgress, p); + backend.eject(drive); + } + p.step = UsbStep::Done; + notify(onProgress, p); +} + +} // namespace openpu diff --git a/src/core/usb_none.cpp b/src/core/usb_none.cpp new file mode 100644 index 0000000..ad64841 --- /dev/null +++ b/src/core/usb_none.cpp @@ -0,0 +1,13 @@ +// Fallback for platforms without a USB backend: listing and formatting are unavailable, +// but writePayload() still works on an already prepared stick. + +#include "openpu/usb.hpp" + +namespace openpu { + +std::unique_ptr makeUsbBackend() +{ + throw UsbError(UsbError::Kind::Unavailable, "no USB backend on this platform"); +} + +} // namespace openpu diff --git a/src/core/usb_udisks.cpp b/src/core/usb_udisks.cpp new file mode 100644 index 0000000..ea97517 --- /dev/null +++ b/src/core/usb_udisks.cpp @@ -0,0 +1,381 @@ +// UDisks2 backend (Linux): enumeration, FAT32 formatting, mounting and ejecting over D-Bus. +// Authorisation is delegated to polkit, so no root privileges are needed in a desktop session. + +#include "openpu/usb.hpp" + +#include +#include +#include +#include +#include +#include + +namespace openpu { + +namespace fs = std::filesystem; + +namespace { + +constexpr const char* kService = "org.freedesktop.UDisks2"; +constexpr const char* kManager = "/org/freedesktop/UDisks2"; +constexpr const char* kIfDrive = "org.freedesktop.UDisks2.Drive"; +constexpr const char* kIfBlock = "org.freedesktop.UDisks2.Block"; +constexpr const char* kIfPartition = "org.freedesktop.UDisks2.Partition"; +constexpr const char* kIfPartitionTable = "org.freedesktop.UDisks2.PartitionTable"; +constexpr const char* kIfFilesystem = "org.freedesktop.UDisks2.Filesystem"; +constexpr const char* kIfLoop = "org.freedesktop.UDisks2.Loop"; +constexpr int kLongTimeoutMs = 30 * 60 * 1000; // formatting a large stick can take a while + +/// Owning GVariant reference. +class Variant { +public: + Variant() = default; + explicit Variant(GVariant* v) : v_(v) {} // takes ownership (sinks floating refs) + Variant(const Variant&) = delete; + Variant& operator=(const Variant&) = delete; + Variant(Variant&& o) noexcept : v_(o.v_) { o.v_ = nullptr; } + Variant& operator=(Variant&& o) noexcept + { + std::swap(v_, o.v_); + return *this; + } + ~Variant() + { + if (v_ != nullptr) + g_variant_unref(v_); + } + GVariant* get() const { return v_; } + explicit operator bool() const { return v_ != nullptr; } + +private: + GVariant* v_ = nullptr; +}; + +class Error { +public: + Error() = default; + Error(const Error&) = delete; + Error& operator=(const Error&) = delete; + ~Error() + { + if (e_ != nullptr) + g_error_free(e_); + } + GError** out() { return &e_; } + GError* get() const { return e_; } + std::string message() const { return e_ != nullptr ? e_->message : "unknown D-Bus error"; } + +private: + GError* e_ = nullptr; +}; + +[[noreturn]] void throwDbus(const Error& err, const std::string& what) +{ + std::string name; + if (err.get() != nullptr) { + gchar* remote = g_dbus_error_get_remote_error(err.get()); + if (remote != nullptr) { + name = remote; + g_free(remote); + } + } + UsbError::Kind kind = UsbError::Kind::Failed; + if (name.find("NotAuthorized") != std::string::npos || name.find("AccessDenied") != std::string::npos) + kind = UsbError::Kind::NotAuthorized; + else if (name.find("DeviceBusy") != std::string::npos) + kind = UsbError::Kind::Busy; + else if (name.find("ServiceUnknown") != std::string::npos || name.find("NoReply") != std::string::npos) + kind = UsbError::Kind::Unavailable; + throw UsbError(kind, what + ": " + err.message()); +} + +std::string getString(GVariant* dict, const char* key) +{ + const gchar* s = nullptr; + return g_variant_lookup(dict, key, "&s", &s) && s != nullptr ? s : ""; +} + +std::string getPath(GVariant* dict, const char* key) +{ + const gchar* s = nullptr; + return g_variant_lookup(dict, key, "&o", &s) && s != nullptr ? s : ""; +} + +std::string getBytestring(GVariant* dict, const char* key) +{ + const gchar* s = nullptr; + return g_variant_lookup(dict, key, "^&ay", &s) && s != nullptr ? s : ""; +} + +bool getBool(GVariant* dict, const char* key) +{ + gboolean b = FALSE; + return g_variant_lookup(dict, key, "b", &b) && b != FALSE; +} + +std::uint64_t getU64(GVariant* dict, const char* key) +{ + guint64 v = 0; + return g_variant_lookup(dict, key, "t", &v) ? static_cast(v) : 0; +} + +std::vector getMountPoints(GVariant* fsDict) +{ + std::vector out; + Variant mps(g_variant_lookup_value(fsDict, "MountPoints", G_VARIANT_TYPE("aay"))); + if (!mps) + return out; + GVariantIter it; + g_variant_iter_init(&it, mps.get()); + GVariant* child = nullptr; + while ((child = g_variant_iter_next_value(&it)) != nullptr) { + Variant owned(child); + const gchar* s = g_variant_get_bytestring(owned.get()); + if (s != nullptr && *s != '\0') + out.emplace_back(s); + } + return out; +} + +/// Snapshot of the UDisks2 object tree: path -> interface -> properties dict (a{sv}). +struct ObjectTree { + std::map> objects; + + GVariant* props(const std::string& path, const char* iface) const + { + auto o = objects.find(path); + if (o == objects.end()) + return nullptr; + auto i = o->second.find(iface); + return i == o->second.end() ? nullptr : i->second.get(); + } +}; + +class UDisksBackend final : public UsbBackend { +public: + UDisksBackend() + { + Error err; + bus_ = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, err.out()); + if (bus_ == nullptr) + throw UsbError(UsbError::Kind::Unavailable, "cannot connect to the system bus: " + err.message()); + const char* allow = std::getenv("OPENPU_USB_ALLOW_LOOP"); // NOLINT(concurrency-mt-unsafe) + allowLoop_ = allow != nullptr && std::string(allow) == "1"; + (void)tree(); // fail early if UDisks2 is not available + } + UDisksBackend(const UDisksBackend&) = delete; + UDisksBackend& operator=(const UDisksBackend&) = delete; + ~UDisksBackend() override { g_object_unref(bus_); } + + std::vector list() override + { + const ObjectTree t = tree(); + std::vector out; + for (const auto& [path, ifaces] : t.objects) { + GVariant* block = t.props(path, kIfBlock); + if (block == nullptr || t.props(path, kIfPartition) != nullptr) + continue; // whole disks only + if (getBool(block, "HintSystem") && t.props(path, kIfLoop) == nullptr) + continue; + const std::string drivePath = getPath(block, "Drive"); + GVariant* drive = drivePath.size() > 1 ? t.props(drivePath, kIfDrive) : nullptr; + + UsbDrive d; + d.id = path; + d.device = getBytestring(block, "PreferredDevice"); + if (d.device.empty()) + d.device = getBytestring(block, "Device"); + d.size = getU64(block, "Size"); + if (drive != nullptr) { + const bool usb = getString(drive, "ConnectionBus") == "usb"; + const bool removable = getBool(drive, "Removable") || getBool(drive, "MediaRemovable"); + if (!usb || !removable || d.size == 0) + continue; + d.vendor = getString(drive, "Vendor"); + d.model = getString(drive, "Model"); + } else if (allowLoop_ && t.props(path, kIfLoop) != nullptr && d.size > 0) { + d.isLoop = true; + d.model = "loop device"; + } else { + continue; + } + collectVolumes(t, path, d); + out.push_back(std::move(d)); + } + std::sort(out.begin(), out.end(), [](const UsbDrive& a, const UsbDrive& b) { return a.device < b.device; }); + return out; + } + + fs::path formatFat32(const UsbDrive& drive, const std::string& label) override + { + requireListed(drive); + unmountAll(drive.id); + + // New MBR partition table on the whole disk. + call(drive.id, kIfBlock, "Format", g_variant_new("(s@a{sv})", "dos", options({{"erase", nullptr}})), + "creating the partition table"); + + // One primary FAT32 (LBA, type 0x0c) partition spanning the disk, formatted vfat. + GVariantBuilder fmt; + g_variant_builder_init(&fmt, G_VARIANT_TYPE("a{sv}")); + g_variant_builder_add(&fmt, "{sv}", "label", g_variant_new_string(label.c_str())); + g_variant_builder_add(&fmt, "{sv}", "update-partition-type", g_variant_new_boolean(FALSE)); + Variant created = call(drive.id, kIfPartitionTable, "CreatePartitionAndFormat", + // (offset, size, type, name, options, format_type, format_options); size 0 = rest of disk + g_variant_new("(ttss@a{sv}s@a{sv})", + static_cast(1024 * 1024), static_cast(0), "0x0c", "", + options({}), "vfat", g_variant_builder_end(&fmt)), + "creating the FAT32 partition"); + const gchar* partition = nullptr; + g_variant_get(created.get(), "(&o)", &partition); + const std::string partPath = partition != nullptr ? partition : ""; + + // The Filesystem interface may show up slightly after the call returns. + for (int i = 0;; ++i) { + Error err; + Variant r(g_dbus_connection_call_sync(bus_, kService, partPath.c_str(), kIfFilesystem, "Mount", + g_variant_new("(@a{sv})", options({})), G_VARIANT_TYPE("(s)"), + G_DBUS_CALL_FLAGS_NONE, kLongTimeoutMs, nullptr, err.out())); + if (r) { + const gchar* mp = nullptr; + g_variant_get(r.get(), "(&s)", &mp); + return mp != nullptr ? fs::path(mp) : fs::path(); + } + if (i >= 20) + throwDbus(err, "mounting the new file system"); + std::this_thread::sleep_for(std::chrono::milliseconds(250)); + } + } + + void eject(const UsbDrive& drive) override + { + unmountAll(drive.id); + const ObjectTree t = tree(); + GVariant* block = t.props(drive.id, kIfBlock); + if (block == nullptr) + return; // already gone + if (t.props(drive.id, kIfLoop) != nullptr) + return; // test loop devices are detached by the caller + const std::string drivePath = getPath(block, "Drive"); + GVariant* d = drivePath.size() > 1 ? t.props(drivePath, kIfDrive) : nullptr; + if (d == nullptr) + return; + if (getBool(d, "CanPowerOff")) + call(drivePath, kIfDrive, "PowerOff", g_variant_new("(@a{sv})", options({})), "powering off the drive"); + else if (getBool(d, "Ejectable")) + call(drivePath, kIfDrive, "Eject", g_variant_new("(@a{sv})", options({})), "ejecting the drive"); + } + +private: + /// a{sv} options; a nullptr value means "omit". Interaction with polkit agents is allowed. + static GVariant* options(std::initializer_list> extra) + { + GVariantBuilder b; + g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}")); + for (const auto& [k, v] : extra) + if (v != nullptr) + g_variant_builder_add(&b, "{sv}", k, v); + return g_variant_builder_end(&b); + } + + Variant call(const std::string& path, const char* iface, const char* method, GVariant* params, + const std::string& what) + { + Error err; + Variant r(g_dbus_connection_call_sync(bus_, kService, path.c_str(), iface, method, params, nullptr, + G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION, kLongTimeoutMs, + nullptr, err.out())); + if (!r) + throwDbus(err, what); + return r; + } + + ObjectTree tree() + { + Error err; + Variant r(g_dbus_connection_call_sync(bus_, kService, kManager, "org.freedesktop.DBus.ObjectManager", + "GetManagedObjects", nullptr, G_VARIANT_TYPE("(a{oa{sa{sv}}})"), + G_DBUS_CALL_FLAGS_NONE, 10000, nullptr, err.out())); + if (!r) + throwDbus(err, "UDisks2 is not available"); + ObjectTree t; + Variant objects(g_variant_get_child_value(r.get(), 0)); + GVariantIter oit; + g_variant_iter_init(&oit, objects.get()); + const gchar* path = nullptr; + GVariant* ifaces = nullptr; + while (g_variant_iter_next(&oit, "{&o@a{sa{sv}}}", &path, &ifaces)) { + Variant ownedIfaces(ifaces); + auto& entry = t.objects[path]; + GVariantIter iit; + g_variant_iter_init(&iit, ownedIfaces.get()); + const gchar* name = nullptr; + GVariant* props = nullptr; + while (g_variant_iter_next(&iit, "{&s@a{sv}}", &name, &props)) + entry.emplace(name, Variant(props)); + } + return t; + } + + static std::vector partitionsOf(const ObjectTree& t, const std::string& wholePath) + { + std::vector parts; + for (const auto& [path, ifaces] : t.objects) { + GVariant* p = t.props(path, kIfPartition); + if (p != nullptr && getPath(p, "Table") == wholePath) + parts.push_back(path); + } + std::sort(parts.begin(), parts.end()); + return parts; + } + + static void collectVolumes(const ObjectTree& t, const std::string& wholePath, UsbDrive& d) + { + std::vector volumes{wholePath}; + const auto parts = partitionsOf(t, wholePath); + volumes.insert(volumes.end(), parts.begin(), parts.end()); + for (const auto& v : volumes) { + if (GVariant* b = t.props(v, kIfBlock); b != nullptr && d.label.empty()) + d.label = getString(b, "IdLabel"); + if (GVariant* f = t.props(v, kIfFilesystem); f != nullptr) { + auto mps = getMountPoints(f); + d.mountPoints.insert(d.mountPoints.end(), mps.begin(), mps.end()); + } + } + } + + void requireListed(const UsbDrive& drive) + { + // Never format something that is not (any more) a removable drive we listed. + const auto drives = list(); + const bool ok = std::any_of(drives.begin(), drives.end(), [&](const UsbDrive& d) { return d.id == drive.id; }); + if (!ok) + throw UsbError(UsbError::Kind::Failed, drive.device + " is not an available removable drive"); + } + + void unmountAll(const std::string& wholePath) + { + const ObjectTree t = tree(); + std::vector volumes{wholePath}; + const auto parts = partitionsOf(t, wholePath); + volumes.insert(volumes.end(), parts.begin(), parts.end()); + for (const auto& v : volumes) { + GVariant* f = t.props(v, kIfFilesystem); + if (f == nullptr || getMountPoints(f).empty()) + continue; + call(v, kIfFilesystem, "Unmount", g_variant_new("(@a{sv})", options({})), "unmounting " + v); + } + } + + GDBusConnection* bus_ = nullptr; + bool allowLoop_ = false; +}; + +} // namespace + +std::unique_ptr makeUsbBackend() +{ + return std::make_unique(); +} + +} // namespace openpu diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ef47458..0f0c314 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -9,6 +9,7 @@ add_executable(openpu_tests test_download.cpp test_archive.cpp test_storage.cpp + test_usb.cpp ) find_package(LibArchive REQUIRED) target_link_libraries(openpu_tests PRIVATE openpu_core openpu_warnings LibArchive::LibArchive) diff --git a/tests/test_usb.cpp b/tests/test_usb.cpp new file mode 100644 index 0000000..d48debb --- /dev/null +++ b/tests/test_usb.cpp @@ -0,0 +1,152 @@ +#include "openpu/archive.hpp" +#include "openpu/usb.hpp" + +#include "test_util.hpp" + +#include +#include +#include + +using namespace openpu; +namespace fs = std::filesystem; + +namespace { + +void makeTar(const fs::path& file, const std::vector>& files) +{ + archive* a = archive_write_new(); + archive_write_set_format_ustar(a); + REQUIRE(archive_write_open_filename(a, file.c_str()) == ARCHIVE_OK); + for (const auto& [name, content] : files) { + archive_entry* e = archive_entry_new(); + archive_entry_set_pathname(e, name.c_str()); + archive_entry_set_filetype(e, AE_IFREG); + archive_entry_set_perm(e, 0644); + archive_entry_set_size(e, static_cast(content.size())); + archive_write_header(a, e); + archive_write_data(a, content.data(), content.size()); + archive_entry_free(e); + } + archive_write_close(a); + archive_write_free(a); +} + +/// Backend that "formats" by wiping a directory, and records the calls. +class FakeUsb final : public UsbBackend { +public: + explicit FakeUsb(fs::path root) : root_(std::move(root)) {} + std::vector calls; + std::string label; + + std::vector list() override + { + UsbDrive d; + d.id = "fake"; + d.device = "/dev/fake"; + d.size = 8000000000ULL; + return {d}; + } + fs::path formatFat32(const UsbDrive&, const std::string& l) override + { + calls.emplace_back("format"); + label = l; + fs::remove_all(root_); + fs::create_directories(root_); + return root_; + } + void eject(const UsbDrive&) override { calls.emplace_back("eject"); } + +private: + fs::path root_; +}; + +} // namespace + +TEST_CASE("volume label sanitising matches the official app") +{ + CHECK(sanitizeLabel("") == "NEW"); + CHECK(sanitizeLabel(" ") == "NEW"); + CHECK(sanitizeLabel("Clé USB 3.0") == "CLUSB30"); + CHECK(sanitizeLabel("my_stick_name_long") == "MY_STICK_NA"); + CHECK(sanitizeLabel("new") == "NEW"); +} + +TEST_CASE("minimum stick size is 2 GB times a power of two") +{ + CHECK(minimumStickSize(0) == 2000000000ULL); + CHECK(minimumStickSize(1000000000ULL) == 2000000000ULL); + CHECK(minimumStickSize(1900000000ULL) == 4000000000ULL); // +10 % > 2 GB + CHECK(minimumStickSize(8391587840ULL + 10626) == 16000000000ULL); // real RCC firmware + license + CHECK(minimumStickSize(2728908800ULL + 10475161600ULL) == 16000000000ULL); // NAC fw + map + CHECK(withMargin(1000) == 1100); +} + +TEST_CASE("payload is written: license folder then archives at the root") +{ + TempDir tmp; + const fs::path lic = tmp.path() / "dl" / "license_ABC.key"; + writeAll(lic, "KEY"); + const fs::path fw = tmp.path() / "dl" / "fw.tar"; + makeTar(fw, {{"UpdateInfo.xml", ""}, {"rcc_update/a.bin", "AAAA"}}); + const fs::path map = tmp.path() / "dl" / "map.tar"; + makeTar(map, {{"map/data.bin", "MM"}, {"UpdateInfo.xml", ""}}); + + UsbWritePlan plan; + plan.license = lic; + plan.archives = {fw, map}; + CHECK(plan.payloadSize() == 3 + 4 + 2); + + const fs::path usb = tmp.path() / "usb"; + std::vector steps; + writePayload(usb, plan, [&](const UsbProgress& p) { + if (steps.empty() || steps.back() != p.step) + steps.push_back(p.step); + }); + CHECK(readAll(usb / "license" / "license_ABC.key") == "KEY"); + CHECK(readAll(usb / "rcc_update" / "a.bin") == "AAAA"); + CHECK(readAll(usb / "map" / "data.bin") == "MM"); + CHECK_FALSE(fs::exists(usb / "UpdateInfo.xml")); + CHECK(steps == std::vector{UsbStep::CopyingLicense, UsbStep::Extracting}); +} + +TEST_CASE("writeToUsb verifies before formatting, then writes and ejects") +{ + TempDir tmp; + const fs::path fw = tmp.path() / "fw.tar"; + makeTar(fw, {{"rcc_update/a.bin", "AAAA"}}); + FakeUsb usb(tmp.path() / "stick"); + const UsbDrive drive = usb.list().front(); + UsbWritePlan plan; + plan.archives = {fw}; + + std::vector steps; + writeToUsb(usb, drive, "my stick", plan, [&](const UsbProgress& p) { + if (steps.empty() || steps.back() != p.step) + steps.push_back(p.step); + }); + CHECK(usb.calls == std::vector{"format", "eject"}); + CHECK(usb.label == "MYSTICK"); + CHECK(readAll(tmp.path() / "stick" / "rcc_update" / "a.bin") == "AAAA"); + CHECK(steps == + std::vector{UsbStep::Verifying, UsbStep::Formatting, UsbStep::Extracting, UsbStep::Ejecting, UsbStep::Done}); + + SUBCASE("a corrupt archive aborts before the stick is erased") + { + writeAll(tmp.path() / "stick" / "keep.txt", "precious"); + writeAll(fw, std::string(2048, 'Z')); + usb.calls.clear(); + CHECK_THROWS_AS(writeToUsb(usb, drive, "x", plan), ArchiveError); + CHECK(usb.calls.empty()); + CHECK(readAll(tmp.path() / "stick" / "keep.txt") == "precious"); + } +} + +TEST_CASE("drive description") +{ + UsbDrive d; + d.vendor = "SanDisk"; + d.model = "Ultra"; + d.device = "/dev/sdb"; + d.size = 32000000000ULL; + CHECK(d.description() == "SanDisk Ultra (/dev/sdb, 32.0 GB)"); +} diff --git a/tools/dev-polkit.sh b/tools/dev-polkit.sh new file mode 100644 index 0000000..f5a14fd --- /dev/null +++ b/tools/dev-polkit.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# DEVELOPMENT ONLY (WSL / test VM): lets the invoking user run UDisks2 operations +# (loop-setup, format, mount, power-off) without a polkit agent, so that the end-to-end +# USB tests can run headless. Never install this on a real desktop machine. +# +# usage: sudo tools/dev-polkit.sh install | remove +set -eu + +RULE=/etc/polkit-1/rules.d/49-openpu-dev.rules +USER_NAME=${SUDO_USER:-} + +case "${1:-}" in +install) + [ -n "$USER_NAME" ] || { echo "run with sudo from your user account" >&2; exit 1; } + cat > "$RULE" </dev/null || true + echo "installed $RULE for user $USER_NAME" + ;; +remove) + rm -f "$RULE" + systemctl restart polkit 2>/dev/null || true + echo "removed $RULE" + ;; +*) + echo "usage: sudo $0 install|remove" >&2 + exit 2 + ;; +esac diff --git a/tools/e2e-usb.sh b/tools/e2e-usb.sh new file mode 100644 index 0000000..59f0063 --- /dev/null +++ b/tools/e2e-usb.sh @@ -0,0 +1,46 @@ +#!/bin/sh +# End-to-end USB test on Linux without a real stick: a sparse disk image is attached as a loop +# device through UDisks2, `openpu-cli write-usb` formats and fills it, then the result is checked +# with sfdisk / fsck.fat / mtools. Needs udisks2, dosfstools, mtools and, in a session without a +# polkit agent (WSL, CI), the rule installed by `sudo tools/dev-polkit.sh install`. +# +# usage: tools/e2e-usb.sh [--license file.key] ... +set -eu + +CLI=$1; shift +# Not /tmp: often a small tmpfs, and the image plus the extracted partition need ~2x the payload. +WORK=$(mktemp -d "${OPENPU_E2E_DIR:-$HOME}/openpu-e2e.XXXXXX") +IMG=$WORK/usb.img +LOOP= +cleanup() { + [ -n "$LOOP" ] && udisksctl loop-delete --no-user-interaction -b "$LOOP" >/dev/null 2>&1 || true + rm -rf "$WORK" +} +trap cleanup EXIT INT TERM + +truncate -s 16G "$IMG" +LOOP=$(udisksctl loop-setup --no-user-interaction -f "$IMG" | grep -o '/dev/loop[0-9]*' | head -1) +echo "loop device: $LOOP" + +OPENPU_USB_ALLOW_LOOP=1 "$CLI" write-usb "$LOOP" --yes --label "openpu e2e" "$@" 2>&1 | tr '\r' '\n' | grep -vE '^\s*$' | tail -2 + +fail() { echo "FAIL: $*" >&2; exit 1; } + +echo "--- partition table" +TABLE=$(sfdisk -d "$IMG") +echo "$TABLE" | grep -q '^label: dos' || fail "no MBR partition table" +echo "$TABLE" | grep -qE 'start= *2048, .*type=c$' || fail "expected one FAT32 LBA (0x0c) partition at 1 MiB" +echo "MBR, partition type 0x0c at 1 MiB: ok" + +echo "--- file system" +dd if="$IMG" of="$WORK/part.img" bs=1M skip=1 conv=sparse status=none +fsck.vfat -n "$WORK/part.img" | tail -1 +minfo -i "$WORK/part.img" :: | grep -q 'disk type="FAT32' || fail "not FAT32" +LABEL=$(mlabel -s -i "$WORK/part.img" :: | sed 's/.*is //; s/ *$//') +[ "$LABEL" = "OPENPUE2E" ] || fail "label is '$LABEL'" +echo "FAT32, label $LABEL: ok" + +echo "--- content" +mdir -/ -b -i "$WORK/part.img" :: | sed 's/license_[0-9A-Fa-f]*\.key/license_.key/' | sort +if mdir -/ -b -i "$WORK/part.img" :: | grep -q 'UpdateInfo.xml'; then fail "UpdateInfo.xml was copied"; fi +echo "PASS"