usb: backend UDisks2 et écriture de la mise à jour sur clé
- API UsbBackend (liste, formatage FAT32, éjection) + implémentation UDisks2 via GDBus : disques USB amovibles uniquement (jamais HintSystem), table MBR + partition 0x0c à 1 Mio formatée vfat, montage, PowerOff ; autorisation déléguée à polkit (pas de root) - writeToUsb : vérification des archives AVANT effacement, formatage, licence dans license/, extraction fw puis carte, éjection - règles de l'app officielle : label assaini (11 car., majuscules, NEW), taille de clé minimale 2/4/8… Go avec marge de 10 % - CLI : usb-list, write-usb (confirmation YES), write-dir - tests : faux backend (ordre des étapes, archive corrompue => clé intacte), labels, tailles - tools/e2e-usb.sh : image loop via UDisks2 + contrôle sfdisk/fsck/mtools ; tools/dev-polkit.sh pour WSL/CI - validé de bout en bout avec le vrai firmware RCC 8,39 Go : MBR, FAT32, label, arborescence, fsck propre, en environ 20 s Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WDASLCiN764v685boRVYar
This commit is contained in:
1 parent
543347a1e6
commit
6a7a2f1ee9
11 files changed
+1047
-8
No files matched your search
@@ -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 <algorithm>
|
||||
#include <csignal>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -36,6 +38,11 @@ void usage()
|
||||
" resuming partial files\n"
|
||||
" verify <file.tar> check the integrity of an update archive\n"
|
||||
" extract <file.tar> <dir> extract an update archive (skips UpdateInfo.xml)\n"
|
||||
" usb-list list removable USB drives\n"
|
||||
" write-usb <device> [--license F] [--label L] [--yes] [--no-eject] <archive.tar>...\n"
|
||||
" ERASE <device>, format FAT32 and write the update\n"
|
||||
" write-dir <dir> [--license F] <archive.tar>...\n"
|
||||
" write the update into an existing directory\n"
|
||||
" raw-devices <VIN> print the raw devices/{VIN} response\n"
|
||||
" raw-updates <VIN> 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<std::string>& 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<std::string>& 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<std::string>& 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<std::string> args)
|
||||
{
|
||||
openpu::CurlOptions curlOptions;
|
||||
@@ -228,11 +361,17 @@ int run(std::vector<std::string> 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';
|
||||
}
|
||||
|
||||
+16
-6
@@ -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()
|
||||
@@ -0,0 +1,102 @@
|
||||
#pragma once
|
||||
|
||||
#include "openpu/cancel.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
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<std::filesystem::path> 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<UsbDrive> 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<UsbBackend> 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<void(const UsbProgress&)>;
|
||||
|
||||
struct UsbWritePlan {
|
||||
std::optional<std::filesystem::path> license; ///< copied to <root>/license/<name>
|
||||
std::vector<std::filesystem::path> 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
|
||||
@@ -0,0 +1,153 @@
|
||||
#include "openpu/usb.hpp"
|
||||
|
||||
#include "openpu/archive.hpp"
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
#include <system_error>
|
||||
|
||||
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<double>(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<unsigned char>(c);
|
||||
if (std::isalnum(uc) != 0 || c == '_') {
|
||||
out.push_back(static_cast<char>(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
|
||||
@@ -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<UsbBackend> makeUsbBackend()
|
||||
{
|
||||
throw UsbError(UsbError::Kind::Unavailable, "no USB backend on this platform");
|
||||
}
|
||||
|
||||
} // namespace openpu
|
||||
@@ -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 <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <gio/gio.h>
|
||||
#include <map>
|
||||
#include <thread>
|
||||
|
||||
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<std::uint64_t>(v) : 0;
|
||||
}
|
||||
|
||||
std::vector<fs::path> getMountPoints(GVariant* fsDict)
|
||||
{
|
||||
std::vector<fs::path> 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<std::string, std::map<std::string, Variant>> 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<UsbDrive> list() override
|
||||
{
|
||||
const ObjectTree t = tree();
|
||||
std::vector<UsbDrive> 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<guint64>(1024 * 1024), static_cast<guint64>(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<std::pair<const char*, GVariant*>> 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<std::string> partitionsOf(const ObjectTree& t, const std::string& wholePath)
|
||||
{
|
||||
std::vector<std::string> 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<std::string> 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<std::string> 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<UsbBackend> makeUsbBackend()
|
||||
{
|
||||
return std::make_unique<UDisksBackend>();
|
||||
}
|
||||
|
||||
} // namespace openpu
|
||||
Reference in new issue
Block a user