// SPDX-License-Identifier: MIT // 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