Files
MontaukOS/tests/smb/mount_harness.cpp
T

651 lines
28 KiB
C++

/*
* mount_harness.cpp
* Host harness for the userspace-filesystem bridge and the smbfs provider
* Copyright (c) 2026 Daniel Hammer
*/
// Compiles the real kernel sources Fs/Vfs.cpp and Fs/UserFs.cpp against the
// scheduler stand-in in kshim/ (every pthread is a "process"), and the real
// src/smbfs/main.cpp against ushim/, into one program:
//
// mount_harness bridge VFS <-> provider protocol, with a
// scripted provider: concurrency, callers
// killed mid-call, timeouts, unmount,
// remount, eject
// mount_harness smb HOST PORT USER PASS SHARE
// VFS calls -> UserFs -> smbfs -> a real
// SMB server, i.e. everything a program
// does on a mounted share except the
// syscall entry itself
#include <Fs/Vfs.hpp>
#include <Fs/UserFs.hpp>
#include <Sched/Scheduler.hpp>
#include <Timekeeping/Timer.hpp>
#include <Common/StatusCodes.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include <pthread.h>
#include <unistd.h>
using namespace montauk::abi;
namespace Vfs = Fs::Vfs;
static int g_failures = 0;
static std::mutex g_checkLock;
static void check(bool ok, const char* what) {
std::lock_guard<std::mutex> lk(g_checkLock);
std::printf(" %s %s\n", ok ? "PASS" : "FAIL", what);
if (!ok) g_failures++;
}
// ============================================================================
// Scheduler / clock stand-ins
// ============================================================================
static thread_local Sched::Process tl_proc;
// Set to make the thread vanish the next time it blocks, the way process exit
// terminates a blocked sibling thread: no unwinding, no cleanup.
static thread_local std::atomic<bool>* tl_vanish = nullptr;
static std::mutex g_wakeLock;
static std::condition_variable g_wakeCv;
static uint64_t g_wakeEpoch = 1;
static std::atomic<uint64_t> g_timeSkew{0};
static void become(int pid, int session = 1) {
tl_proc.pid = pid;
tl_proc.sessionId = session;
tl_proc.killPending = false;
}
namespace Sched {
int GetCurrentPid() { return tl_proc.pid; }
int GetCurrentTid() { return tl_proc.pid; }
Process* GetCurrentProcessPtr() { return &tl_proc; }
Process* GetCurrentThreadPtr() { return &tl_proc; }
bool HasCapability(uint64_t) { return false; }
uint64_t ObserveObjectWake(void*) {
std::lock_guard<std::mutex> lk(g_wakeLock);
return g_wakeEpoch;
}
bool BlockOnObjectSince(void*, uint64_t timeoutMs, uint64_t observed) {
{
std::unique_lock<std::mutex> lk(g_wakeLock);
// Short slices: deadlines are measured on the skewable test clock.
uint64_t slice = (timeoutMs == 0 || timeoutMs > 20) ? 20 : timeoutMs;
g_wakeCv.wait_for(lk, std::chrono::milliseconds(slice),
[&] { return g_wakeEpoch != observed; });
}
if (tl_vanish != nullptr && tl_vanish->load()) pthread_exit(nullptr);
return true;
}
void WakeObjectWaiters(void*) {
std::lock_guard<std::mutex> lk(g_wakeLock);
g_wakeEpoch++;
g_wakeCv.notify_all();
}
}
namespace Timekeeping {
uint64_t GetMilliseconds() {
auto now = std::chrono::steady_clock::now().time_since_epoch();
return (uint64_t)std::chrono::duration_cast<std::chrono::milliseconds>(now).count() +
g_timeSkew.load();
}
}
static void sleep_ms(int ms) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); }
// ============================================================================
// Scripted provider (bridge test)
// ============================================================================
static uint8_t pattern(uint64_t offset) { return (uint8_t)((offset * 131) ^ (offset >> 9)); }
struct FakeProvider {
int pid = 300;
int session = 1;
int drive = -1;
std::atomic<bool> paused{false};
std::atomic<bool> stop{false};
std::atomic<int> served{0};
std::atomic<int> closes{0};
std::atomic<int> ejects{0};
std::atomic<int> badWrites{0};
std::thread thread;
void start() {
std::atomic<bool> ready{false};
thread = std::thread([&] {
become(pid, session);
UserFsMountParams p{};
std::snprintf(p.label, sizeof(p.label), "fake");
std::snprintf(p.fsType, sizeof(p.fsType), "test");
std::snprintf(p.source, sizeof(p.source), "test://fake");
drive = Fs::UserFs::Mount(&p);
ready = true;
if (drive < 0) return;
run();
});
while (!ready) sleep_ms(1);
}
void run() {
static thread_local std::vector<uint8_t> data(USERFS_MAX_DATA), reply(USERFS_MAX_DATA);
UserFsRequest req;
while (!stop) {
if (paused) { sleep_ms(2); continue; }
int got = Fs::UserFs::Recv(drive, &req, data.data(), USERFS_MAX_DATA, 20);
if (got < 0) return; // unmounted
if (got == 0) continue;
uint32_t len = 0;
int64_t result = UnsupportedOp;
switch (req.op) {
case USERFS_OP_OPEN:
case USERFS_OP_CREATE:
result = std::strcmp(req.path, "/missing") ? 7 : (int64_t)NoSuchPath;
break;
case USERFS_OP_CLOSE: closes++; break;
case USERFS_OP_GETSIZE: result = 250000; break;
case USERFS_OP_READ: {
uint64_t end = 250000;
uint64_t n = req.offset >= end ? 0 : std::min<uint64_t>(req.size, end - req.offset);
for (uint64_t i = 0; i < n; i++) reply[i] = pattern(req.offset + i);
len = (uint32_t)n;
result = (int64_t)n;
break;
}
case USERFS_OP_WRITE:
for (uint32_t i = 0; i < req.dataLen; i++)
if (data[i] != pattern(req.offset + i)) { badWrites++; break; }
result = req.dataLen;
break;
case USERFS_OP_READDIR: {
static const char names[] = "alpha.txt\0beta/\0gamma.bin\0";
if (req.offset == 0) {
std::memcpy(reply.data(), names, sizeof(names) - 1);
len = sizeof(names) - 1;
result = 3;
} else {
result = 0;
}
break;
}
case USERFS_OP_STAT: {
if (!std::strcmp(req.path, "/missing")) { result = NoSuchPath; break; }
FileStat st{};
st.size = 1234;
st.mtime = 1000000000;
st.isDir = !std::strcmp(req.path, "/") ? 1 : 0;
std::memcpy(reply.data(), &st, sizeof(st));
len = sizeof(st);
result = 0;
break;
}
case USERFS_OP_DELETE:
case USERFS_OP_MKDIR:
case USERFS_OP_RENAME:
case USERFS_OP_SETTIMES: result = 0; break;
case USERFS_OP_UNMOUNT: ejects++; break;
}
served++;
if (req.id != 0) Fs::UserFs::Reply(drive, req.id, result, reply.data(), len);
}
}
// Emulate the provider process dying.
void die() {
stop = true;
if (thread.joinable()) thread.join();
Fs::UserFs::OnProcessExit(pid);
}
};
static std::string drive_path(int drive, const char* rest) {
return std::to_string(drive) + ":" + rest;
}
static bool stat_ok(int drive, const char* path, uint64_t* size = nullptr) {
Vfs::StatInfo info;
if (Vfs::VfsStat(drive_path(drive, path).c_str(), info) != 0) return false;
if (size) *size = info.size;
return true;
}
static int run_bridge() {
std::printf("bridge: VFS <-> provider protocol\n");
become(100);
Vfs::Initialize();
FakeProvider fp;
fp.start();
int d = fp.drive;
check(d == Fs::UserFs::FirstDrive, "mount returns the first provider drive");
check(Vfs::IsDriveRegistered(d) && Vfs::VfsDriveKind(d) == Vfs::DriveKindNetwork, "drive registered as network kind");
char label[40], type[16];
Vfs::VfsDriveLabel(d, label, sizeof(label));
Vfs::VfsDriveFsType(d, type, sizeof(type));
check(!std::strcmp(label, "fake") && !std::strcmp(type, "test"), "label and type");
UserFsInfo info;
check(Fs::UserFs::Info(d, &info) == Success && info.providerPid == 300 &&
!std::strcmp(info.source, "test://fake"), "info reports provider and source");
uint64_t size = 0;
check(stat_ok(d, "/file", &size) && size == 1234, "stat round trip");
check(!stat_ok(d, "/missing"), "stat failure propagates");
Vfs::StatInfo root;
check(Vfs::VfsStat(drive_path(d, "").c_str(), root) == 0 && root.isDir, "bare drive path reaches the provider as '/'");
Vfs::BackendFile f;
check(Vfs::OpenBackendFile(drive_path(d, "/missing").c_str(), f) != 0, "open failure propagates");
check(Vfs::OpenBackendFile(drive_path(d, "/file").c_str(), f) == 0, "open");
check(Vfs::GetBackendFileSize(f) == 250000, "getsize");
std::vector<uint8_t> buf(300000);
int n = Vfs::ReadBackendFile(f, buf.data(), 0, buf.size());
bool good = n == 250000;
for (int i = 0; good && i < n; i++) good = buf[i] == pattern(i);
check(good, "read 250000 bytes across several chunks, short at EOF");
n = Vfs::ReadBackendFile(f, buf.data(), 70000, 10);
check(n == 10 && buf[0] == pattern(70000), "read at an offset");
for (size_t i = 0; i < 150000; i++) buf[i] = pattern(5 + i);
check(Vfs::WriteBackendFile(f, buf.data(), 5, 150000) == 150000 && fp.badWrites == 0,
"write 150000 bytes across chunks, data intact");
Vfs::CloseBackendFile(f);
for (int i = 0; i < 100 && fp.closes == 0; i++) sleep_ms(5);
check(fp.closes == 1, "close delivered without a reply");
const char* names[8];
n = Vfs::VfsReadDirAt(drive_path(d, "/").c_str(), names, 8, 0);
check(n == 3 && !std::strcmp(names[0], "alpha.txt") && !std::strcmp(names[1], "beta/") &&
!std::strcmp(names[2], "gamma.bin"), "readdir names");
check(Vfs::VfsReadDirAt(drive_path(d, "/").c_str(), names, 8, 3) == 0, "readdir past the end");
check(Vfs::VfsMkdir(drive_path(d, "/x").c_str()) == 0 &&
Vfs::VfsRename(drive_path(d, "/x").c_str(), drive_path(d, "/y").c_str()) == 0 &&
Vfs::VfsDelete(drive_path(d, "/y").c_str()) == 0 &&
Vfs::VfsSetTimes(drive_path(d, "/file").c_str(), 1, 2) == 0, "mkdir / rename / delete / settimes");
// More callers than request slots, all at once.
{
std::atomic<int> okCount{0};
std::vector<std::thread> ts;
for (int t = 0; t < 40; t++) {
ts.emplace_back([&, t] {
become(1000 + t);
for (int i = 0; i < 25; i++) if (stat_ok(d, "/file")) okCount++;
});
}
for (auto& t : ts) t.join();
check(okCount == 1000, "40 concurrent callers x 25 calls (more callers than slots)");
}
// The provider calling into its own drive must fail, not wait on itself.
{
std::atomic<int> rc{0};
std::thread t([&] { become(300); Vfs::StatInfo si; rc = Vfs::VfsStat(drive_path(d, "/file").c_str(), si); });
t.join();
check(rc != 0, "provider calling its own drive fails at once");
}
// Callers killed while blocked: 40 of them, more than twice the slots.
{
fp.paused = true;
sleep_ms(50);
int before = fp.served;
for (int i = 0; i < 40; i++) {
std::atomic<bool> vanish{false};
std::thread t([&, i] {
become(2000 + i);
tl_vanish = &vanish;
stat_ok(d, "/file");
});
sleep_ms(15);
vanish = true;
t.join();
Fs::UserFs::OnProcessExit(2000 + i);
}
fp.paused = false;
check(stat_ok(d, "/file"), "drive still works after 40 callers died mid-call");
sleep_ms(50);
check(fp.served - before == 1, "requests of dead callers are never delivered");
}
// A provider that stops answering: the caller gives up after the timeout.
{
fp.paused = true;
sleep_ms(50);
std::atomic<int> state{0};
std::thread t([&] { become(101); state = stat_ok(d, "/file") ? 1 : 2; });
sleep_ms(100);
check(state == 0, "caller waits while the provider is busy");
g_timeSkew += 46000;
t.join();
check(state == 2, "caller times out after 45 s of silence");
fp.paused = false;
check(stat_ok(d, "/file"), "drive works again once the provider answers");
}
// A late answer to a caller that gave up is refused, not misdelivered.
{
become(300);
check(Fs::UserFs::Reply(d, 999999, 0, nullptr, 0) == NotFound, "reply to an unknown request is rejected");
become(100);
std::vector<uint8_t> scratch(USERFS_MAX_DATA);
UserFsRequest rq;
check(Fs::UserFs::Recv(d, &rq, scratch.data(), USERFS_MAX_DATA, 0) == NoDevice,
"only the provider may receive requests");
}
// Eject requests.
{
become(400, 2);
check(Fs::UserFs::Unmount(d) == PermissionDenied, "eject from another session is refused");
become(100, 1);
check(Fs::UserFs::Unmount(d) == Success, "eject from the same session is accepted");
for (int i = 0; i < 100 && fp.ejects == 0; i++) sleep_ms(5);
check(fp.ejects == 1 && Vfs::IsDriveRegistered(d), "provider is told to unmount; drive stays until it does");
}
// Unmount with a caller blocked, then mount the same slot again.
{
fp.paused = true;
sleep_ms(50);
std::atomic<int> state{0};
std::thread t([&] { become(102); state = stat_ok(d, "/file") ? 1 : 2; });
sleep_ms(80);
fp.die();
t.join();
check(state == 2, "blocked caller fails when the provider exits");
check(!Vfs::IsDriveRegistered(d) && !stat_ok(d, "/file"), "drive is gone after the provider exits");
FakeProvider second;
second.pid = 301;
second.start();
check(second.drive == d, "the drive number is reused by the next mount");
check(stat_ok(d, "/file"), "remounted drive works");
// A file handle from the old mount must not reach the new provider.
int closesBefore = second.closes;
check(Vfs::ReadBackendFile(f, buf.data(), 0, 16) < 0, "stale file handle is rejected after a remount");
Vfs::CloseBackendFile(f);
sleep_ms(60);
check(second.closes == closesBefore, "stale close is not delivered to the new provider");
become(301);
check(Fs::UserFs::Unmount(d) == Success, "provider unmounts its own drive");
become(100);
check(!Vfs::IsDriveRegistered(d), "drive removed on provider unmount");
second.die();
}
// Every slot in use.
{
std::vector<FakeProvider*> all;
for (int i = 0; i < Fs::UserFs::MaxMounts; i++) {
auto* p = new FakeProvider;
p->pid = 500 + i;
p->start();
all.push_back(p);
}
bool distinct = true;
for (int i = 0; i < Fs::UserFs::MaxMounts; i++) distinct = distinct && all[i]->drive == Fs::UserFs::FirstDrive + i;
check(distinct, "16 simultaneous mounts get drives 32-47");
become(600);
UserFsMountParams p{};
check(Fs::UserFs::Mount(&p) == Busy, "a 17th mount is refused");
become(100);
check(stat_ok(all[9]->drive, "/file"), "one of many mounts answers");
for (auto* p2 : all) { p2->die(); delete p2; }
int drives[64];
check(Vfs::VfsDriveList(drives, 64) == 0, "all drives gone after their providers exit");
}
return 0;
}
// ============================================================================
// Real smbfs provider (end-to-end test)
// ============================================================================
extern "C" void smbfs_entry();
static std::string g_args;
static std::mutex g_outLock;
static std::string g_out;
static std::atomic<bool> g_providerExited{false};
static std::atomic<int> g_providerExitCode{-1};
static const int kProviderPid = 50;
extern "C" {
int h_userfs_mount(const void* p) { return Fs::UserFs::Mount((const UserFsMountParams*)p); }
int h_userfs_recv(int d, void* req, void* data, uint32_t max, uint64_t t) {
return Fs::UserFs::Recv(d, (UserFsRequest*)req, (uint8_t*)data, max, t);
}
int h_userfs_reply(int d, uint64_t id, int64_t res, const void* data, uint32_t len) {
return Fs::UserFs::Reply(d, id, res, (const uint8_t*)data, len);
}
int h_userfs_unmount(int d) { return Fs::UserFs::Unmount(d); }
int h_userfs_info(int d, void* out) { return Fs::UserFs::Info(d, (UserFsInfo*)out); }
void h_print(const char* text) {
std::lock_guard<std::mutex> lk(g_outLock);
g_out += text;
}
void h_exit(int code) {
// What the kernel does when the provider process exits.
Fs::UserFs::OnProcessExit(kProviderPid);
g_providerExitCode = code;
g_providerExited = true;
pthread_exit(nullptr);
}
void h_getargs(char* buf, uint64_t max) { std::snprintf(buf, max, "%s", g_args.c_str()); }
uint64_t h_milliseconds() { return Timekeeping::GetMilliseconds(); }
}
static int run_smb(const char* host, const char* port, const char* user, const char* pass, const char* share) {
std::printf("end to end: VFS -> UserFs -> smbfs -> //%s:%s/%s\n", host, port, share);
become(100);
Vfs::Initialize();
g_args = std::string("\"//") + host + "/" + share + "\" --user \"" + user + "\" --port " + port +
" --label \"Test Share\"";
setenv("SMB_PASSWORD", pass, 1);
std::thread provider([] { become(kProviderPid); smbfs_entry(); });
int d = -1;
for (int i = 0; i < 400 && d < 0 && !g_providerExited; i++) {
sleep_ms(25);
std::lock_guard<std::mutex> lk(g_outLock);
if (g_out.rfind("OK ", 0) == 0 && g_out.find('\n') != std::string::npos) d = std::atoi(g_out.c_str() + 3);
}
{
std::lock_guard<std::mutex> lk(g_outLock);
std::printf(" smbfs said: %s", g_out.empty() ? "(nothing)\n" : g_out.c_str());
}
check(d == Fs::UserFs::FirstDrive, "smbfs mounted the share and reported the drive");
if (d < 0) { provider.join(); return 1; }
check(getenv("SMB_PASSWORD") == nullptr, "smbfs removed the password from its environment");
char label[40], type[16];
Vfs::VfsDriveLabel(d, label, sizeof(label));
Vfs::VfsDriveFsType(d, type, sizeof(type));
check(!std::strcmp(label, "Test Share") && !std::strcmp(type, "smb") &&
Vfs::VfsDriveKind(d) == Vfs::DriveKindNetwork, "drive label, type and kind");
auto P = [&](const char* rest) { return drive_path(d, rest); };
Vfs::StatInfo st;
check(Vfs::VfsStat(P("/").c_str(), st) == 0 && st.isDir, "stat the share root");
check(Vfs::VfsStat(P("/nope/nothing").c_str(), st) != 0, "stat a missing path fails");
// Clean up after an earlier run.
const char* names[256];
for (;;) {
int n = Vfs::VfsReadDirAt(P("/e2e/many").c_str(), names, 128, 0);
if (n <= 0) break;
for (int i = 0; i < n; i++) Vfs::VfsDelete((P("/e2e/many/") + names[i]).c_str());
}
for (const char* p : {"/e2e/many", "/e2e/big.bin", "/e2e/moved.bin", "/e2e/note.txt", "/e2e/sub", "/e2e"})
Vfs::VfsDelete(P(p).c_str());
check(Vfs::VfsMkdir(P("/e2e").c_str()) == 0, "mkdir");
check(Vfs::VfsMkdir(P("/e2e").c_str()) != 0, "mkdir of an existing directory fails");
check(Vfs::VfsStat(P("/e2e").c_str(), st) == 0 && st.isDir, "new directory is visible");
Vfs::BackendFile f;
check(Vfs::OpenBackendFile(P("/e2e/note.txt").c_str(), f) != 0, "open a missing file fails");
check(Vfs::CreateBackendFile(P("/e2e/note.txt").c_str(), f) == 0, "create a file");
check(Vfs::BackendFileCanWrite(f), "file handle is writable");
const char* text = "written through the MontaukOS VFS\n";
check(Vfs::WriteBackendFile(f, (const uint8_t*)text, 0, std::strlen(text)) == (int)std::strlen(text), "write");
check(Vfs::GetBackendFileSize(f) == std::strlen(text), "size after write");
Vfs::CloseBackendFile(f);
check(Vfs::OpenBackendFile(P("/e2e/note.txt").c_str(), f) == 0, "reopen");
char back[128] = {};
int n = Vfs::ReadBackendFile(f, (uint8_t*)back, 0, sizeof(back));
check(n == (int)std::strlen(text) && !std::memcmp(back, text, (size_t)n), "read back what was written");
check(Vfs::ReadBackendFile(f, (uint8_t*)back, 5000, 16) == 0, "read past the end returns 0");
// Append through a handle obtained with open (not create).
check(Vfs::WriteBackendFile(f, (const uint8_t*)"more", std::strlen(text), 4) == 4, "write through an opened handle");
Vfs::CloseBackendFile(f);
check(Vfs::VfsStat(P("/e2e/note.txt").c_str(), st) == 0 && !st.isDir && st.size == std::strlen(text) + 4,
"stat sees the new size");
// A file larger than several transfer chunks.
std::vector<uint8_t> big(700000), got(700000);
for (size_t i = 0; i < big.size(); i++) big[i] = pattern(i * 7);
check(Vfs::CreateBackendFile(P("/e2e/big.bin").c_str(), f) == 0 &&
Vfs::WriteBackendFile(f, big.data(), 0, big.size()) == (int)big.size(), "write 700000 bytes");
Vfs::CloseBackendFile(f);
check(Vfs::OpenBackendFile(P("/e2e/big.bin").c_str(), f) == 0 &&
Vfs::ReadBackendFile(f, got.data(), 0, got.size()) == (int)got.size() && got == big,
"read 700000 bytes back intact");
n = Vfs::ReadBackendFile(f, got.data(), 654321, 1000);
check(n == 1000 && !std::memcmp(got.data(), big.data() + 654321, 1000), "read at a large offset");
Vfs::CloseBackendFile(f);
// Several programs reading at once.
{
std::atomic<int> okCount{0};
std::vector<std::thread> ts;
for (int t = 0; t < 6; t++) {
ts.emplace_back([&, t] {
become(700 + t);
Vfs::BackendFile tf;
std::vector<uint8_t> part(100000);
if (Vfs::OpenBackendFile(P("/e2e/big.bin").c_str(), tf) != 0) return;
uint64_t off = (uint64_t)t * 90000;
if (Vfs::ReadBackendFile(tf, part.data(), off, part.size()) == (int)part.size() &&
!std::memcmp(part.data(), big.data() + off, part.size())) okCount++;
Vfs::CloseBackendFile(tf);
});
}
for (auto& t : ts) t.join();
check(okCount == 6, "6 concurrent readers each get the right bytes");
}
check(Vfs::VfsRename(P("/e2e/big.bin").c_str(), P("/e2e/moved.bin").c_str()) == 0, "rename");
check(Vfs::VfsStat(P("/e2e/big.bin").c_str(), st) != 0 &&
Vfs::VfsStat(P("/e2e/moved.bin").c_str(), st) == 0 && st.size == big.size(), "rename took effect");
check(Vfs::VfsMkdir(P("/e2e/sub").c_str()) == 0, "mkdir nested");
n = Vfs::VfsReadDirAt(P("/e2e").c_str(), names, 128, 0);
bool sawFile = false, sawDir = false, sawNote = false;
for (int i = 0; i < n; i++) {
sawFile = sawFile || !std::strcmp(names[i], "moved.bin");
sawDir = sawDir || !std::strcmp(names[i], "sub/");
sawNote = sawNote || !std::strcmp(names[i], "note.txt");
}
check(n == 3 && sawFile && sawDir && sawNote, "readdir lists files, and directories with a trailing slash");
check(Vfs::VfsReadDirAt(P("/e2e/").c_str(), names, 128, 0) == 3, "readdir with a trailing slash");
// A directory too large for one reply page: page through it as Files does.
check(Vfs::VfsMkdir(P("/e2e/many").c_str()) == 0, "mkdir for the large directory");
bool made = true;
for (int i = 0; i < 200 && made; i++) {
char name[96];
std::snprintf(name, sizeof(name), "/e2e/many/entry-with-a-longer-name-%04d.txt", i);
made = Vfs::CreateBackendFile(P(name).c_str(), f) == 0;
Vfs::CloseBackendFile(f);
}
std::vector<std::string> all;
int pages = 0;
for (;;) {
n = Vfs::VfsReadDirAt(P("/e2e/many").c_str(), names, 128, (int)all.size());
if (n <= 0) break;
pages++;
for (int i = 0; i < n; i++) all.push_back(names[i]);
}
std::vector<bool> seen(200, false);
bool unique = true;
for (auto& s : all) {
int idx = std::atoi(s.c_str() + s.size() - 8);
if (idx < 0 || idx >= 200 || seen[idx]) unique = false; else seen[idx] = true;
}
check(made && all.size() == 200 && unique && pages >= 2, "200 entries paged through in several reads, none lost or repeated");
bool gone = true;
for (auto& s : all) gone = gone && Vfs::VfsDelete((P("/e2e/many/") + s).c_str()) == 0;
check(gone && Vfs::VfsReadDirAt(P("/e2e/many").c_str(), names, 128, 0) == 0, "delete them all; listing is empty");
check(Vfs::VfsDelete(P("/e2e").c_str()) != 0, "deleting a non-empty directory fails");
check(Vfs::VfsDelete(P("/e2e/many").c_str()) == 0 && Vfs::VfsDelete(P("/e2e/sub").c_str()) == 0 &&
Vfs::VfsDelete(P("/e2e/moved.bin").c_str()) == 0 && Vfs::VfsDelete(P("/e2e/note.txt").c_str()) == 0 &&
Vfs::VfsDelete(P("/e2e").c_str()) == 0, "delete files and directories");
check(Vfs::VfsStat(P("/e2e").c_str(), st) != 0, "everything is gone");
// The server goes away and comes back (SMB_RESTART restarts it): an open
// file must keep working, on a new session, without the caller noticing
// more than one failed call.
if (const char* restart = getenv("SMB_RESTART")) {
check(Vfs::CreateBackendFile(P("/reconnect.txt").c_str(), f) == 0 &&
Vfs::WriteBackendFile(f, (const uint8_t*)"before", 0, 6) == 6, "file open before the server restarts");
check(std::system(restart) == 0, "server restarted");
bool recovered = false;
for (int i = 0; i < 20 && !recovered; i++) {
recovered = Vfs::VfsStat(P("/reconnect.txt").c_str(), st) == 0;
if (!recovered) sleep_ms(500);
}
check(recovered, "share reachable again after the server restart");
check(Vfs::WriteBackendFile(f, (const uint8_t*)" after", 6, 6) == 6, "handle from before the restart still writes");
char both[32] = {};
check(Vfs::ReadBackendFile(f, (uint8_t*)both, 0, sizeof(both)) == 12 &&
!std::memcmp(both, "before after", 12), "and reads back both halves");
Vfs::CloseBackendFile(f);
check(Vfs::VfsDelete(P("/reconnect.txt").c_str()) == 0, "delete after reconnect");
}
// Eject, as Files' Disconnect does.
UserFsInfo info;
check(Fs::UserFs::Info(d, &info) == Success && info.providerPid == kProviderPid &&
std::string(info.source) == std::string("smb://") + host + "/" + share, "info names the share");
check(Fs::UserFs::Unmount(d) == Success, "eject request accepted");
provider.join();
check(g_providerExited && g_providerExitCode == 0, "smbfs logged off and exited cleanly");
check(!Vfs::IsDriveRegistered(d), "drive is gone after the eject");
return 0;
}
int main(int argc, char** argv) {
if (argc >= 2 && !std::strcmp(argv[1], "bridge")) {
run_bridge();
} else if (argc >= 7 && !std::strcmp(argv[1], "smb")) {
run_smb(argv[2], argv[3], argv[4], argv[5], argv[6]);
} else {
std::fprintf(stderr, "usage: mount_harness bridge | smb HOST PORT USER PASS SHARE\n");
return 2;
}
std::printf("%s (%d failure%s)\n", g_failures ? "FAILED" : "ALL PASS", g_failures, g_failures == 1 ? "" : "s");
return g_failures ? 1 : 0;
}