feat: add SMB networking support

This commit is contained in:
daniel committed 2026-11-22 08:43:18 +01:00
1 parent 6665750528
commit 2af2e90606
55 files changed
+7456 -158

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
#pragma once
#include <sched.h>
namespace Arch { inline void Pause() { sched_yield(); } }
+2
View File
@@ -0,0 +1,2 @@
#pragma once
namespace Arch { struct SyscallFrame; }
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <atomic>
#include <sched.h>
namespace kcp {
class Mutex {
std::atomic_flag flag = ATOMIC_FLAG_INIT;
public:
void Acquire() { while (flag.test_and_set(std::memory_order_acquire)) sched_yield(); }
bool TryAcquire() { return !flag.test_and_set(std::memory_order_acquire); }
void Release() { flag.clear(std::memory_order_release); }
};
using Spinlock = Mutex;
}
+2
View File
@@ -0,0 +1,2 @@
#pragma once
#include <cstring>
+2
View File
@@ -0,0 +1,2 @@
#pragma once
#include <cstring>
+19
View File
@@ -0,0 +1,19 @@
#pragma once
// Host stand-in for the kernel scheduler: every pthread is a "process".
#include <atomic>
#include <cstdint>
namespace Sched {
struct Process {
int pid = -1;
int sessionId = 0;
std::atomic<bool> killPending{false};
};
int GetCurrentPid();
int GetCurrentTid();
Process* GetCurrentProcessPtr();
Process* GetCurrentThreadPtr();
bool HasCapability(uint64_t capability);
uint64_t ObserveObjectWake(void* object);
bool BlockOnObjectSince(void* object, uint64_t timeoutMs, uint64_t observedWake);
void WakeObjectWaiters(void* object);
}
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include <cstdint>
namespace Kt {
enum KernelLogLevel { INFO, OK, WARNING, ERROR };
struct KernelLogStream {
KernelLogStream(KernelLogLevel, const char*) {}
template <typename T> KernelLogStream& operator<<(const T&) { return *this; }
};
}
+3
View File
@@ -0,0 +1,3 @@
#pragma once
#include <cstdint>
namespace Timekeeping { uint64_t GetMilliseconds(); }
+650
View File
@@ -0,0 +1,650 @@
/*
* 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;
}
+87
View File
@@ -0,0 +1,87 @@
#!/bin/sh
# run.sh - Build the SMB client library for the host and test it.
#
# Three layers:
# smb_test vectors crypto / NTLM / SPNEGO known answers
# mount_harness bridge the kernel's userspace-filesystem bridge
# smb_test live, mount_harness smb
# the library, then the whole mount path (VFS ->
# UserFs -> smbfs), against a real SMB server
# The first two always run. The live tests need impacket's smbserver:
# python3 -m venv /tmp/smbvenv && /tmp/smbvenv/bin/pip install impacket
# SMB_PYTHON=/tmp/smbvenv/bin/python tests/smb/run.sh
# Or point it at a real server instead:
# SMB_HOST=nas SMB_USER=me SMB_PASS=secret SMB_SHARE=scratch tests/smb/run.sh
set -e
HERE=$(cd "$(dirname "$0")" && pwd)
ROOT=$(cd "$HERE/../.." && pwd)
OUT=${SMB_TEST_OUT:-$(mktemp -d)}
BEARSSL=$ROOT/programs/lib/bearssl
LIB=$ROOT/programs/lib/smb
mkdir -p "$OUT/bearssl"
for f in "$BEARSSL"/src/codec/enc*.c "$BEARSSL"/src/codec/dec*.c \
"$BEARSSL"/src/hash/md5.c "$BEARSSL"/src/hash/sha2small.c \
"$BEARSSL"/src/mac/hmac.c \
"$BEARSSL"/src/symcipher/aes_ct.c "$BEARSSL"/src/symcipher/aes_ct_enc.c \
"$BEARSSL"/src/symcipher/aes_ct_cbcenc.c; do
cc -O2 -I "$BEARSSL/inc" -I "$BEARSSL/src" -c "$f" -o "$OUT/bearssl/$(basename "$f" .c).o"
done
c++ -std=gnu++20 -O1 -g -Wall -Wextra -Wno-unused-parameter -fsanitize=address,undefined \
-I "$ROOT/programs/include" -I "$BEARSSL/inc" \
"$HERE/smb_test.cpp" "$LIB/smb.cpp" "$LIB/ntlm.cpp" "$LIB/crypto.cpp" \
"$OUT"/bearssl/*.o -o "$OUT/smb_test"
"$OUT/smb_test" vectors
# The mount path: the real kernel Fs/Vfs.cpp + Fs/UserFs.cpp and the real
# smbfs daemon, built for the host against the stand-ins in kshim/ and ushim/.
KSRC=$ROOT/kernel/src
CXXF="-std=gnu++20 -O1 -g -Wall -Wextra -Wno-unused-parameter -fsanitize=address,undefined -pthread"
mkdir -p "$OUT/mount"
for f in "$KSRC/Fs/Vfs.cpp" "$KSRC/Fs/UserFs.cpp" "$HERE/mount_harness.cpp"; do
c++ $CXXF -I "$HERE/kshim" -I "$KSRC" -c "$f" -o "$OUT/mount/k_$(basename "$f" .cpp).o"
done
for f in "$LIB/smb.cpp" "$LIB/ntlm.cpp" "$LIB/crypto.cpp" "$LIB/montauk_io.cpp"; do
c++ $CXXF -I "$HERE/ushim" -I "$ROOT/programs/include" -I "$BEARSSL/inc" \
-c "$f" -o "$OUT/mount/u_$(basename "$f" .cpp).o"
done
c++ $CXXF -D_start=smbfs_entry -I "$HERE/ushim" -I "$ROOT/programs/include" \
-c "$ROOT/programs/src/smbfs/main.cpp" -o "$OUT/mount/u_smbfs.o"
c++ $CXXF "$OUT"/mount/*.o "$OUT"/bearssl/*.o -o "$OUT/mount_harness"
"$OUT/mount_harness" bridge
if [ -n "$SMB_HOST" ]; then
"$OUT/smb_test" live "$SMB_HOST" "${SMB_PORT:-445}" "$SMB_USER" "$SMB_PASS" "$SMB_SHARE"
"$OUT/mount_harness" smb "$SMB_HOST" "${SMB_PORT:-445}" "$SMB_USER" "$SMB_PASS" "$SMB_SHARE"
elif [ -n "$SMB_PYTHON" ]; then
SHARE_DIR=$OUT/share
mkdir -p "$SHARE_DIR"
PORT=${SMB_PORT:-4455}
PIDFILE=$OUT/server.pid
start_server() {
"$SMB_PYTHON" "$HERE/server.py" "$PORT" "$SHARE_DIR" >> "$OUT/server.log" 2>&1 &
echo $! > "$PIDFILE"
}
start_server
trap 'kill $(cat "$PIDFILE") 2>/dev/null' EXIT
sleep 2
"$OUT/smb_test" live 127.0.0.1 "$PORT" tester 'S3cret-pass!' scratch
# Restart command for the reconnect test: stop the server, start another.
cat > "$OUT/restart.sh" <<RESTART
#!/bin/sh
kill \$(cat "$PIDFILE") 2>/dev/null
sleep 1
"$SMB_PYTHON" "$HERE/server.py" "$PORT" "$SHARE_DIR" >> "$OUT/server.log" 2>&1 &
echo \$! > "$PIDFILE"
sleep 2
RESTART
chmod +x "$OUT/restart.sh"
SMB_RESTART="$OUT/restart.sh" "$OUT/mount_harness" smb 127.0.0.1 "$PORT" tester 'S3cret-pass!' scratch
else
echo "live tests skipped (set SMB_PYTHON or SMB_HOST; see the header of this script)"
fi
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env python3
# server.py - Throwaway SMB2 server for tests/smb/run.sh (needs impacket).
# Usage: server.py PORT SHARE_DIR (user "tester", password "S3cret-pass!", share "scratch")
import sys
from impacket import smbserver
from impacket.ntlm import compute_lmhash, compute_nthash
port = int(sys.argv[1])
path = sys.argv[2]
password = "S3cret-pass!"
server = smbserver.SimpleSMBServer(listenAddress="127.0.0.1", listenPort=port)
server.addShare("SCRATCH", path, "test share")
server.setSMB2Support(True)
server.addCredential("tester", 0, compute_lmhash(password), compute_nthash(password))
server.setSMBChallenge("")
server.start()
+397
View File
@@ -0,0 +1,397 @@
/*
* smb_test.cpp
* Host test harness for the SMB client library (programs/lib/smb)
* Copyright (c) 2026 Daniel Hammer
*/
// Builds the library for the host and runs it over a POSIX socket.
//
// smb_test vectors crypto / NTLM known-answer tests
// smb_test live HOST PORT USER PASS SHARE end-to-end file operations
//
// tests/smb/run.sh starts a throwaway impacket SMB server and runs both.
#include <smb/smb.hpp>
#include "../../programs/lib/smb/internal.hpp"
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
using namespace smb;
using namespace smb::detail;
static int g_failures = 0;
static void check(bool ok, const char* what) {
std::printf(" %s %s\n", ok ? "PASS" : "FAIL", what);
if (!ok) g_failures++;
}
static std::vector<uint8_t> unhex(const char* s) {
std::vector<uint8_t> out;
while (s[0] && s[1]) {
unsigned v;
std::sscanf(s, "%2x", &v);
out.push_back((uint8_t)v);
s += 2;
}
return out;
}
static bool eq(const uint8_t* got, const char* hex, size_t n) {
auto want = unhex(hex);
return want.size() == n && std::memcmp(got, want.data(), n) == 0;
}
// ---- Known-answer tests ----
static void run_vectors() {
std::printf("crypto vectors\n");
uint8_t out[32];
// RFC 1320
md4((const uint8_t*)"", 0, out);
check(eq(out, "31d6cfe0d16ae931b73c59d7e0c089c0", 16), "MD4 empty");
md4((const uint8_t*)"abc", 3, out);
check(eq(out, "a448017aaf21d8525fc10ae87aa6729d", 16), "MD4 abc");
const char* longMsg = "12345678901234567890123456789012345678901234567890123456789012345678901234567890";
md4((const uint8_t*)longMsg, 80, out);
check(eq(out, "e33b4ddc9c38f2199c3e7b164fcc0536", 16), "MD4 80 bytes");
// RFC 2202 HMAC-MD5 case 2, RFC 4231 HMAC-SHA256 case 2
hmac_md5((const uint8_t*)"Jefe", 4, (const uint8_t*)"what do ya want ", 16,
(const uint8_t*)"for nothing?", 12, out);
check(eq(out, "750c783e6ab0b503eaa86e310a5db738", 16), "HMAC-MD5");
hmac_sha256((const uint8_t*)"Jefe", 4, (const uint8_t*)"what do ya want for nothing?", 28,
nullptr, 0, out);
check(eq(out, "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843", 32), "HMAC-SHA256");
// RFC 4493 AES-CMAC
auto key = unhex("2b7e151628aed2a6abf7158809cf4f3c");
auto m = unhex("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
"30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710");
aes_cmac(key.data(), m.data(), 0, out);
check(eq(out, "bb1d6929e95937287fa37d129b756746", 16), "AES-CMAC len 0");
aes_cmac(key.data(), m.data(), 16, out);
check(eq(out, "070a16b46b4d4144f79bdd9dd04a287c", 16), "AES-CMAC len 16");
aes_cmac(key.data(), m.data(), 40, out);
check(eq(out, "dfa66747de9ae63030ca32611497c827", 16), "AES-CMAC len 40");
aes_cmac(key.data(), m.data(), 64, out);
check(eq(out, "51f0bebf7e3b9d92fc49741779363cfe", 16), "AES-CMAC len 64");
// SMB 3.0 signing key derivation; reference computed with Python's hmac
// (SP800-108 counter mode over HMAC-SHA256).
{
uint8_t k[16];
for (int i = 0; i < 16; i++) k[i] = (uint8_t)i;
smb3_kdf(k, "SMB2AESCMAC", 12, "SmbSign", 8, out);
check(eq(out, "6234814cbb8ea9227440ebfeb5eacbe1", 16), "SMB3 signing key KDF");
}
// MS-NLMP 4.2.4 (NTLMv2): user "User", domain "Domain", password "Password".
std::printf("NTLMv2 (MS-NLMP 4.2.4)\n");
{
// CHALLENGE_MESSAGE from 4.2.4.3
auto challenge = unhex(
"4e544c4d53535000020000000c000c003800000033828ae20123456789abcdef"
"00000000000000002400240044000000060070170000000f5300650072007600"
"6500720002000c0044006f006d00610069006e0001000c005300650072007600"
"6500720000000000");
NtlmAuthParams p;
p.user = "User";
p.password = "Password";
p.domain = "Domain";
p.anonymous = false;
std::memset(p.clientChallenge, 0xaa, 8);
p.fallbackTime = 0;
uint8_t msg[1024];
uint8_t sessionKey[16];
int n = ntlm_authenticate(challenge.data(), challenge.size(), p, msg, sizeof(msg), sessionKey);
check(n > 0, "authenticate message built");
if (n > 0) {
uint16_t ntLen = get16(msg + 20);
uint32_t ntOff = get32(msg + 24);
check(ntLen >= 16 && eq(msg + ntOff, "68cd0ab851e51c96aabc927bebef6a1c", 16), "NTProofStr");
check(eq(sessionKey, "8de40ccadbc14a82f15cb0ad0de95ca3", 16), "SessionBaseKey");
uint32_t lmOff = get32(msg + 16);
check(eq(msg + lmOff, "86c35097ac9cec102554764a57cccc19aaaaaaaaaaaaaaaa", 24), "LMv2 response");
}
}
std::printf("SPNEGO\n");
{
uint8_t tok[NTLM_NEGOTIATE_LEN];
ntlm_negotiate(tok);
uint8_t blob[256];
int n = spnego_wrap(tok, sizeof(tok), true, blob, sizeof(blob));
check(n > 0 && blob[0] == 0x60 && (size_t)blob[1] + 2 == (size_t)n, "NegTokenInit framing");
n = spnego_wrap(tok, sizeof(tok), false, blob, sizeof(blob));
const uint8_t* inner = nullptr;
size_t innerLen = 0;
check(n > 0 && spnego_unwrap(blob, (size_t)n, &inner, &innerLen) &&
innerLen == sizeof(tok) && std::memcmp(inner, tok, sizeof(tok)) == 0, "NegTokenResp round trip");
}
std::printf("text\n");
{
uint8_t w[64];
int n = utf8_to_utf16("/a//b\xC3\xA9/\xF0\x9F\x98\x80/", w, sizeof(w), true);
char back[64];
utf16_to_utf8(w, (uint32_t)n, back, sizeof(back));
check(n == 14 && std::strcmp(back, "a\\b\xC3\xA9\\\xF0\x9F\x98\x80") == 0, "path UTF-8 <-> UTF-16");
Url u;
check(parse_url("smb://WORK;[email protected]:4455/media/films/2020/", &u) &&
!std::strcmp(u.host, "nas.local") && u.port == 4455 && !std::strcmp(u.share, "media") &&
!std::strcmp(u.path, "films/2020") && !std::strcmp(u.user, "alice") &&
!std::strcmp(u.domain, "WORK"), "parse_url full");
check(parse_url("\\\\nas\\share", &u) && !std::strcmp(u.host, "nas") &&
!std::strcmp(u.share, "share") && u.path[0] == 0 && u.port == 0, "parse_url UNC");
check(!parse_url("smb://", &u), "parse_url empty");
}
}
// ---- POSIX transport ----
static int posix_send(void* ctx, const void* data, uint32_t len) {
int fd = *(int*)ctx;
const char* p = (const char*)data;
while (len > 0) {
ssize_t r = ::send(fd, p, len, MSG_NOSIGNAL);
if (r <= 0) return -1;
p += r;
len -= (uint32_t)r;
}
return 0;
}
static int posix_recv(void* ctx, void* buf, uint32_t len, uint32_t timeoutMs) {
int fd = *(int*)ctx;
pollfd pfd{fd, POLLIN, 0};
int pr = ::poll(&pfd, 1, (int)timeoutMs);
if (pr == 0) return 0;
if (pr < 0) return -1;
ssize_t r = ::recv(fd, buf, len, 0);
return r > 0 ? (int)r : -1;
}
static void posix_random(void*, void* buf, uint32_t len) {
FILE* f = std::fopen("/dev/urandom", "rb");
if (f == nullptr || std::fread(buf, 1, len, f) != len) std::abort();
std::fclose(f);
}
static int dial(const char* host, int port) {
addrinfo hints{};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
addrinfo* res = nullptr;
char portStr[16];
std::snprintf(portStr, sizeof(portStr), "%d", port);
if (getaddrinfo(host, portStr, &hints, &res) != 0) return -1;
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd >= 0 && ::connect(fd, res->ai_addr, res->ai_addrlen) != 0) { ::close(fd); fd = -1; }
freeaddrinfo(res);
return fd;
}
// ---- Live test ----
struct Listing {
std::vector<DirEntry> entries;
};
static bool collect(void* ctx, const DirEntry& e) {
((Listing*)ctx)->entries.push_back(e);
return true;
}
static const DirEntry* find(const Listing& l, const char* name) {
for (auto& e : l.entries) if (!std::strcmp(e.name, name)) return &e;
return nullptr;
}
static int run_live(const char* host, int port, const char* user, const char* pass, const char* share) {
std::printf("live test against %s:%d share %s as '%s'\n", host, port, share, user);
int fd = dial(host, port);
if (fd < 0) { std::printf(" cannot connect\n"); return 1; }
Io io{&fd, posix_send, posix_recv, posix_random};
// Wrong password must be refused before anything else is tried.
if (user[0]) {
int fd2 = dial(host, port);
Io io2{&fd2, posix_send, posix_recv, posix_random};
Client bad;
Credentials wrong{user, "definitely-not-the-password", ""};
int r = connect(&bad, io2, host, wrong);
check(r == ERR_AUTH, "wrong password -> ERR_AUTH");
disconnect(&bad);
::close(fd2);
}
Client c;
Credentials creds{user, pass, ""};
int r = connect(&c, io, host, creds);
std::printf(" connect: %d (%s), dialect 0x%04x, signing %d, guest %d\n", r, status_text(r),
c.dialect, c.signing, c.guest);
check(r == OK, "connect + logon");
if (r != OK) { disconnect(&c); return 1; }
check(echo(&c) == OK, "echo");
ShareInfo shares[32];
int ns = list_shares(&c, shares, 32);
std::printf(" shares: %d\n", ns);
bool sawShare = false;
for (int i = 0; i < ns; i++) {
std::printf(" %-16s type %u%s %s\n", shares[i].name, shares[i].type,
shares[i].hidden ? " (hidden)" : "", shares[i].comment);
if (!strcasecmp(shares[i].name, share)) sawShare = true;
}
check(ns > 0 && sawShare, "list_shares finds the test share");
uint32_t tree = 0;
check(tree_connect(&c, "no-such-share-xyz", &tree) == ERR_BAD_SHARE, "bad share -> ERR_BAD_SHARE");
r = tree_connect(&c, share, &tree);
check(r == OK, "tree_connect");
if (r != OK) { disconnect(&c); return 1; }
FileInfo info;
check(stat(&c, tree, "", &info) == OK && info.isDir, "stat share root");
check(stat(&c, tree, "does/not/exist", &info) == ERR_NOT_FOUND, "stat missing -> ERR_NOT_FOUND");
// Directory with a non-ASCII name.
const char* dir = "t\xC3\xA9st dir";
remove(&c, tree, "t\xC3\xA9st dir/big.bin");
remove(&c, tree, "t\xC3\xA9st dir/renamed.txt");
remove(&c, tree, "t\xC3\xA9st dir/hello.txt");
remove(&c, tree, dir);
check(mkdir(&c, tree, dir) == OK, "mkdir");
check(mkdir(&c, tree, dir) == ERR_EXISTS, "mkdir again -> ERR_EXISTS");
check(stat(&c, tree, dir, &info) == OK && info.isDir, "stat new directory");
// Small file.
std::string path = std::string(dir) + "/hello.txt";
FileId id;
check(open(&c, tree, path.c_str(), OPEN_READ, &id) == ERR_NOT_FOUND, "open missing -> ERR_NOT_FOUND");
r = open(&c, tree, path.c_str(), OPEN_CREATE, &id);
check(r == OK, "create file");
const char* text = "hello from MontaukOS\n";
check(write(&c, tree, id, 0, text, (uint32_t)std::strlen(text)) == (int)std::strlen(text), "write");
uint64_t size = 0;
check(file_size(&c, tree, id, &size) == OK && size == std::strlen(text), "file_size");
check(close(&c, tree, id) == OK, "close");
check(open(&c, tree, path.c_str(), OPEN_CREATE_NEW, &id) == ERR_EXISTS, "create new on existing -> ERR_EXISTS");
char rbuf[128] = {};
r = open(&c, tree, path.c_str(), OPEN_READ, &id, &info);
check(r == OK && info.size == std::strlen(text) && !info.isDir, "open for read + info");
int n = read(&c, tree, id, 0, rbuf, sizeof(rbuf));
check(n == (int)std::strlen(text) && !std::memcmp(rbuf, text, (size_t)n), "read back");
check(read(&c, tree, id, 1000, rbuf, sizeof(rbuf)) == 0, "read past EOF -> 0");
n = read(&c, tree, id, 6, rbuf, 4);
check(n == 4 && !std::memcmp(rbuf, "from", 4), "read at offset");
close(&c, tree, id);
// Large file crossing several MAX_IO chunks.
std::vector<uint8_t> big(300000);
for (size_t i = 0; i < big.size(); i++) big[i] = (uint8_t)((i * 2654435761u) >> 13);
std::string bigPath = std::string(dir) + "/big.bin";
r = open(&c, tree, bigPath.c_str(), OPEN_CREATE, &id);
bool ok = r == OK;
for (size_t off = 0; ok && off < big.size();) {
int w = write(&c, tree, id, off, big.data() + off, (uint32_t)(big.size() - off));
if (w <= 0) { ok = false; break; }
off += (size_t)w;
}
close(&c, tree, id);
check(ok, "write 300000 bytes");
std::vector<uint8_t> back(big.size());
r = open(&c, tree, bigPath.c_str(), OPEN_READWRITE, &id, &info);
ok = r == OK && info.size == big.size();
for (size_t off = 0; ok && off < back.size();) {
int g = read(&c, tree, id, off, back.data() + off, (uint32_t)(back.size() - off));
if (g <= 0) { ok = false; break; }
off += (size_t)g;
}
close(&c, tree, id);
check(ok && back == big, "read 300000 bytes back intact");
// Rename, times, listing.
std::string renamed = std::string(dir) + "/renamed.txt";
check(rename(&c, tree, path.c_str(), renamed.c_str()) == OK, "rename");
check(stat(&c, tree, path.c_str(), &info) == ERR_NOT_FOUND, "old name gone");
check(rename(&c, tree, bigPath.c_str(), renamed.c_str()) == ERR_EXISTS, "rename onto existing -> ERR_EXISTS");
r = set_times(&c, tree, renamed.c_str(), 0, 1000000000);
check(r == OK, "set_times");
// impacket's server accepts FileBasicInformation but does not apply it.
if (stat(&c, tree, renamed.c_str(), &info) == OK && info.mtime != 1000000000)
std::printf(" NOTE server ignored set_times (mtime %lld)\n", (long long)info.mtime);
Listing l;
n = list_dir(&c, tree, dir, collect, &l);
check(n == 2 && find(l, "renamed.txt") && find(l, "big.bin"), "list_dir");
const DirEntry* be = find(l, "big.bin");
check(be && be->info.size == big.size() && !be->info.isDir, "list_dir sizes");
Listing root;
n = list_dir(&c, tree, "/", collect, &root);
const DirEntry* de = find(root, dir);
check(n >= 1 && de && de->info.isDir, "root listing shows the directory (UTF-8 name)");
r = list_dir(&c, tree, renamed.c_str(), collect, &l);
check(r == ERR_NOT_DIR || r == ERR_INVALID, "list_dir on a file is refused");
// Many entries: the listing must span several QUERY_DIRECTORY replies.
std::string many = std::string(dir) + "/many";
mkdir(&c, tree, many.c_str());
ok = true;
for (int i = 0; i < 300 && ok; i++) {
char name[160];
std::snprintf(name, sizeof(name), "%s/a-file-with-a-fairly-long-name-to-fill-the-reply-%04d.dat", many.c_str(), i);
ok = open(&c, tree, name, OPEN_CREATE, &id) == OK && close(&c, tree, id) == OK;
}
Listing ml;
n = list_dir(&c, tree, many.c_str(), collect, &ml);
check(ok && n == 300, "list_dir with 300 entries");
for (int i = 0; i < 300; i++) {
char name[160];
std::snprintf(name, sizeof(name), "%s/a-file-with-a-fairly-long-name-to-fill-the-reply-%04d.dat", many.c_str(), i);
remove(&c, tree, name);
}
check(remove(&c, tree, many.c_str()) == OK, "remove emptied directory");
// Removal.
check(remove(&c, tree, dir) == ERR_NOT_EMPTY, "remove non-empty dir -> ERR_NOT_EMPTY");
check(remove(&c, tree, renamed.c_str()) == OK, "remove file");
check(remove(&c, tree, bigPath.c_str()) == OK, "remove big file");
check(remove(&c, tree, dir) == OK, "remove directory");
check(stat(&c, tree, dir, &info) == ERR_NOT_FOUND, "directory gone");
check(tree_disconnect(&c, tree) == OK, "tree_disconnect");
disconnect(&c);
::close(fd);
return 0;
}
int main(int argc, char** argv) {
if (argc >= 2 && !std::strcmp(argv[1], "vectors")) {
run_vectors();
} else if (argc >= 7 && !std::strcmp(argv[1], "live")) {
run_live(argv[2], std::atoi(argv[3]), argv[4], argv[5], argv[6]);
} else {
std::fprintf(stderr, "usage: smb_test vectors | live 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;
}
+94
View File
@@ -0,0 +1,94 @@
// Host stand-in for <montauk/syscall.h>, for running smbfs and the SMB
// library's MontaukOS transport inside tests/smb/mount_harness.
#pragma once
#include <Api/Syscall.hpp>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <cstdio>
#include <cstdint>
extern "C" {
int h_userfs_mount(const void* params);
int h_userfs_recv(int drive, void* req, void* data, uint32_t dataMax, uint64_t timeoutMs);
int h_userfs_reply(int drive, uint64_t id, int64_t result, const void* data, uint32_t len);
int h_userfs_unmount(int drive);
int h_userfs_info(int drive, void* out);
void h_print(const char* text);
[[noreturn]] void h_exit(int code);
void h_getargs(char* buf, uint64_t max);
uint64_t h_milliseconds();
}
namespace montauk {
inline int userfs_mount(const abi::UserFsMountParams* p) { return h_userfs_mount(p); }
inline int userfs_recv(int d, abi::UserFsRequest* r, void* data, uint32_t max, uint64_t t) {
return h_userfs_recv(d, r, data, max, t);
}
inline int userfs_reply(int d, uint64_t id, int64_t res, const void* data = nullptr, uint32_t len = 0) {
return h_userfs_reply(d, id, res, data, len);
}
inline int userfs_unmount(int d) { return h_userfs_unmount(d); }
inline int userfs_info(int d, abi::UserFsInfo* out) { return h_userfs_info(d, out); }
inline void print(const char* s) { h_print(s); }
inline int64_t write_log(const char* s) { fprintf(stderr, " %s\n", s); return 0; }
inline bool terminal_attached() { return false; }
[[noreturn]] inline void exit(int code = 0) { h_exit(code); }
inline int getargs(char* buf, uint64_t max) { h_getargs(buf, max); return 0; }
inline uint64_t get_milliseconds() { return h_milliseconds(); }
inline void sleep_ms(uint64_t ms) { usleep((useconds_t)ms * 1000); }
inline int64_t getrandom(void* buf, uint32_t len) {
FILE* f = fopen("/dev/urandom", "rb");
size_t n = f ? fread(buf, 1, len, f) : 0;
if (f) fclose(f);
return (int64_t)n;
}
// Sockets, with the MontaukOS conventions: recv returns 0 when nothing is
// waiting and a negative value once the peer has closed.
inline uint32_t resolve(const char* host) {
addrinfo hints{};
hints.ai_family = AF_INET;
addrinfo* res = nullptr;
if (getaddrinfo(host, nullptr, &hints, &res) != 0 || !res) return 0;
uint32_t ip = ((sockaddr_in*)res->ai_addr)->sin_addr.s_addr;
freeaddrinfo(res);
return ip;
}
inline int socket(int) { return ::socket(AF_INET, SOCK_STREAM, 0); }
inline int connect(int fd, uint32_t ip, uint16_t port) {
sockaddr_in a{};
a.sin_family = AF_INET;
a.sin_port = htons(port);
a.sin_addr.s_addr = ip;
return ::connect(fd, (sockaddr*)&a, sizeof(a));
}
inline int closesocket(int fd) { return ::close(fd); }
inline int send(int fd, const void* data, uint32_t len) {
ssize_t r = ::send(fd, data, len, MSG_NOSIGNAL);
return r < 0 ? -1 : (int)r;
}
inline int recv(int fd, void* buf, uint32_t len) {
ssize_t r = ::recv(fd, buf, len, MSG_DONTWAIT);
if (r > 0) return (int)r;
if (r == 0) return -1;
return (errno == EAGAIN || errno == EWOULDBLOCK) ? 0 : -1;
}
inline uint32_t wait_handle(int fd, uint32_t wanted, uint64_t timeoutMs = ~0ULL) {
pollfd p{fd, 0, 0};
if (wanted & abi::IPC_SIGNAL_READABLE) p.events |= POLLIN;
if (wanted & abi::IPC_SIGNAL_WRITABLE) p.events |= POLLOUT;
int ms = timeoutMs > 60000 ? 60000 : (int)timeoutMs;
if (::poll(&p, 1, ms) < 0) return (uint32_t)-1;
uint32_t out = 0;
if (p.revents & POLLIN) out |= abi::IPC_SIGNAL_READABLE;
if (p.revents & POLLOUT) out |= abi::IPC_SIGNAL_WRITABLE;
if (p.revents & (POLLHUP | POLLERR)) out |= abi::IPC_SIGNAL_PEER_CLOSED;
return out;
}
}