Files
opu/src/core/usb_haiku.cpp
T
yann64andClaude Opus 5.5 962343f220
CI / Linux arm64 (push) Waiting to run
CI / Linux x86_64 (push) Waiting to run
CI / ASan + UBSan (push) Waiting to run
haiku: working USB backend, symlink-safe extraction
- usb_haiku.cpp: each disk device transaction kept minimal, because
  Haiku R1/beta6 rejects or hangs on combined ones: erase foreign
  content, delete old MBR partitions, create the 0x0c partition
  ("FAT 32-bit, LBA-mapped", with "active false" parameters) and format
  FAT32 are separate commits; Uninitialize is never used on an MBR
- OPENPU_DEBUG=1 traces the Haiku disk device steps on stderr
- extractTar resolves the destination first: SECURE_SYMLINKS refused
  destinations under a symlink (/tmp on Haiku)
- check.sh: clang-tidy skips sources not built on Linux
- validated in the Haiku VM: write-usb on the virtual stick gives an MBR,
  a FAT32 partition at 1 MiB, the label, license/ and the archive tree
  without UpdateInfo.xml, with identical checksums; 53 unit tests pass

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WDASLCiN764v685boRVYar
2026-11-28 23:49:13 +01:00

267 lines
11 KiB
C++

// SPDX-License-Identifier: MIT
// Haiku USB backend: enumeration, FAT32 formatting, mounting and ejecting through the Storage Kit
// disk device API (BDiskDeviceRoster / BDiskDevice / BPartition), the same API DriveSetup uses.
// Haiku is single-user, so no authorisation step is involved.
#include "openpu/usb.hpp"
#include <DiskDevice.h>
#include <DiskDeviceRoster.h>
#include <DiskDeviceTypes.h>
#include <Partition.h>
#include <Path.h>
#include <String.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
namespace openpu {
namespace fs = std::filesystem;
namespace {
constexpr off_t kPartitionOffset = off_t{1024} * 1024; // 1 MiB, like the Linux backend
// Partition type as named by the "intel" partitioning add-on (MBR type 0x0c, as on Linux).
// Not kPartitionTypeFAT32: that one is the *file system* name ("FAT32 File System").
constexpr const char* kMbrTypeFat32Lba = "FAT 32-bit, LBA-mapped";
// The intel add-on rejects a NULL parameter string when the job runs; DriveSetup always sends this.
constexpr const char* kMbrChildParameters = "active false\n";
std::string statusText(status_t s)
{
return std::strerror(s); // NOLINT(concurrency-mt-unsafe): Haiku's strerror is thread-safe
}
[[noreturn]] void fail(const std::string& what, status_t status)
{
throw UsbError(UsbError::Kind::Failed, what + ": " + statusText(status));
}
/// Step tracing on stderr when OPENPU_DEBUG is set (diagnosing disk device jobs).
void trace(const std::string& step)
{
static const bool enabled = std::getenv("OPENPU_DEBUG") != nullptr; // NOLINT(concurrency-mt-unsafe)
if (enabled)
(void)std::fprintf(stderr, "[usb_haiku] %s\n", step.c_str());
}
bool startsWith(const char* s, const char* prefix)
{
return s != nullptr && std::strncmp(s, prefix, std::strlen(prefix)) == 0;
}
/// Calls `fn` for the device itself and every partition below it.
template <typename F>
void forEachPartition(BPartition* p, F&& fn)
{
fn(p);
for (int32 i = 0; i < p->CountChildren(); ++i)
forEachPartition(p->ChildAt(i), fn);
}
bool hostsBootVolume(BDiskDevice& device)
{
bool boot = false;
forEachPartition(&device, [&](BPartition* p) {
BPath mp;
if (p->IsMounted() && p->GetMountPoint(&mp) == B_OK && std::strcmp(mp.Path(), "/boot") == 0)
boot = true;
});
return boot;
}
partition_id parseId(const std::string& id)
{
try {
return static_cast<partition_id>(std::stoi(id));
} catch (const std::exception&) {
throw UsbError(UsbError::Kind::Failed, "invalid drive id " + id);
}
}
/// Disk systems are looked up by short name on some Haiku versions and by "pretty" name on others.
status_t initialize(BPartition* p, const char* shortName, const char* prettyName, const char* name,
const char* parameters)
{
status_t s = p->Initialize(shortName, name, parameters);
if (s != B_OK)
s = p->Initialize(prettyName, name, parameters);
return s;
}
class HaikuUsbBackend final : public UsbBackend {
public:
std::vector<UsbDrive> list() override
{
std::vector<UsbDrive> out;
BDiskDeviceRoster roster;
BDiskDevice device;
roster.RewindDevices();
while (roster.GetNextDevice(&device) == B_OK) {
BPath path;
if (device.GetPath(&path) != B_OK || !startsWith(path.Path(), "/dev/disk/usb/"))
continue;
if (!device.HasMedia() || device.IsReadOnlyMedia() || device.Size() <= 0 || hostsBootVolume(device))
continue;
UsbDrive d;
d.id = std::to_string(device.ID());
d.device = path.Path();
d.size = static_cast<std::uint64_t>(device.Size());
if (device.Name() != nullptr)
d.model = device.Name();
forEachPartition(&device, [&](BPartition* p) {
if (d.label.empty() && p->ContentType() != nullptr)
d.label = p->ContentName().String();
BPath mp;
if (p->IsMounted() && p->GetMountPoint(&mp) == B_OK)
d.mountPoints.emplace_back(mp.Path());
});
out.push_back(std::move(d));
}
return out;
}
fs::path formatFat32(const UsbDrive& drive, const std::string& label) override
{
const partition_id id = parseId(drive.id);
BDiskDeviceRoster roster;
BDiskDevice device;
status_t s = roster.GetDeviceWithID(id, &device);
if (s != B_OK)
fail("USB drive " + drive.device + " not found", s);
BPath path;
if (device.GetPath(&path) != B_OK || !startsWith(path.Path(), "/dev/disk/usb/") || hostsBootVolume(device))
throw UsbError(UsbError::Kind::Failed, drive.device + " is not a removable USB drive");
trace("unmount");
unmountAll(device);
const bool hasMbr = device.ContentType() != nullptr && std::strcmp(device.ContentType(), kPartitionTypeIntel) == 0;
trace(std::string("content type: ") + (device.ContentType() != nullptr ? device.ContentType() : "(none)"));
if (device.ContentType() != nullptr && !hasMbr) {
// Other content (GPT, a file system without partition table...): erase it in its own
// transaction. Uninitialize + Initialize in one transaction hangs the disk device
// manager on Haiku R1/beta6.
if ((s = device.PrepareModifications()) != B_OK)
fail("cannot modify " + drive.device, s);
if ((s = device.Uninitialize()) != B_OK || (s = device.CommitModifications()) != B_OK) {
device.CancelModifications();
fail("cannot erase " + drive.device, s);
}
if ((s = roster.GetDeviceWithID(id, &device)) != B_OK)
fail("USB drive " + drive.device + " not found", s);
}
if (hasMbr && device.CountChildren() > 0) {
// Keep the existing MBR and drop its partitions (Uninitialize would hang, see above).
// Own transaction too: freed space is not reusable within the same transaction.
if ((s = device.PrepareModifications()) != B_OK)
fail("cannot modify " + drive.device, s);
for (int32 i = device.CountChildren() - 1; i >= 0 && s == B_OK; --i) {
trace("delete partition " + std::to_string(i));
s = device.DeleteChild(i);
}
if (s != B_OK || (s = device.CommitModifications()) != B_OK) {
device.CancelModifications();
fail("cannot delete the existing partitions", s);
}
if ((s = roster.GetDeviceWithID(id, &device)) != B_OK)
fail("USB drive " + drive.device + " not found", s);
}
trace("prepare modifications");
if ((s = device.PrepareModifications()) != B_OK)
fail("cannot modify " + drive.device, s);
try {
if (!hasMbr) {
trace("initialize intel");
if ((s = initialize(&device, "intel", kPartitionTypeIntel, nullptr, nullptr)) != B_OK)
fail("cannot create the MBR partition table", s);
}
off_t start = kPartitionOffset;
off_t size = device.Size() - start;
BString name;
if ((s = device.ValidateCreateChild(&start, &size, kMbrTypeFat32Lba, &name, kMbrChildParameters)) != B_OK)
fail("cannot create the FAT32 partition", s);
trace("create child at " + std::to_string(start) + " size " + std::to_string(size));
if ((s = device.CreateChild(start, size, kMbrTypeFat32Lba, nullptr, kMbrChildParameters)) != B_OK)
fail("cannot create the FAT32 partition", s);
trace("commit partition table");
if ((s = device.CommitModifications()) != B_OK)
fail("cannot write the partition table to " + drive.device, s);
} catch (...) {
device.CancelModifications();
throw;
}
// Format in a separate transaction: initializing a partition created in the same
// transaction fails when the job runs ("Invalid Argument").
if ((s = roster.GetDeviceWithID(id, &device)) != B_OK || device.CountChildren() == 0)
fail("the new partition is not visible", s != B_OK ? s : B_ENTRY_NOT_FOUND);
if ((s = device.PrepareModifications()) != B_OK)
fail("cannot modify " + drive.device, s);
try {
trace("initialize fat");
// No parameters: the FAT driver picks FAT32 for volumes this size (checked by the e2e test).
if ((s = initialize(device.ChildAt(0), "fat", "FAT32 File System", label.c_str(), nullptr)) != B_OK)
fail("cannot format the FAT32 partition", s);
trace("commit format");
if ((s = device.CommitModifications()) != B_OK)
fail("cannot format " + drive.device, s);
} catch (...) {
device.CancelModifications();
throw;
}
// Mount the new file system (re-read the device: the committed state is a new snapshot).
if ((s = roster.GetDeviceWithID(id, &device)) != B_OK || device.CountChildren() == 0)
fail("the new partition is not visible", s != B_OK ? s : B_ENTRY_NOT_FOUND);
BPartition* part = device.ChildAt(0);
if (!part->IsMounted() && (s = part->Mount()) != B_OK)
fail("cannot mount the new file system", s);
BPath mountPoint;
if ((s = part->GetMountPoint(&mountPoint)) != B_OK)
fail("cannot locate the mount point", s);
return mountPoint.Path();
}
void eject(const UsbDrive& drive) override
{
BDiskDeviceRoster roster;
BDiskDevice device;
if (roster.GetDeviceWithID(parseId(drive.id), &device) != B_OK)
return; // already gone
unmountAll(device); // flushes the FAT
// Not every USB mass-storage device supports the eject command; unmounting is enough then.
(void)device.Eject(true);
}
private:
static void unmountAll(BDiskDevice& device)
{
status_t failure = B_OK;
forEachPartition(&device, [&](BPartition* p) {
if (p->IsMounted()) {
const status_t s = p->Unmount();
if (s != B_OK)
failure = s;
}
});
if (failure != B_OK)
throw UsbError(UsbError::Kind::Busy, "cannot unmount the USB drive: " + statusText(failure));
}
};
} // namespace
std::unique_ptr<UsbBackend> makeUsbBackend()
{
return std::make_unique<HaikuUsbBackend>();
}
} // namespace openpu