diff --git a/.gitignore b/.gitignore index 0e4525c..9d1f31b 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,8 @@ programs/lib/libc/liblibc-full.a programs/lib/libc/*.o programs/lib/libc/obj/ programs/lib/libloader/liblibloader.a +programs/lib/smb/libsmb.a +programs/lib/smb/obj/ programs/gui/icons/ CLAUDE.md programs/lib/bearssl diff --git a/kernel/src/Api/BuildNo.hpp b/kernel/src/Api/BuildNo.hpp index 8812502..4b875a1 100644 --- a/kernel/src/Api/BuildNo.hpp +++ b/kernel/src/Api/BuildNo.hpp @@ -12,4 +12,4 @@ #pragma once -#define MONTAUK_BUILD_NUMBER 132 +#define MONTAUK_BUILD_NUMBER 137 diff --git a/kernel/src/Api/Filesystem.hpp b/kernel/src/Api/Filesystem.hpp index 7cd8964..c22d4f5 100644 --- a/kernel/src/Api/Filesystem.hpp +++ b/kernel/src/Api/Filesystem.hpp @@ -212,6 +212,8 @@ namespace montauk::abi { } static int Sys_DriveKind(int driveNumber) { + int kind = Fs::Vfs::VfsDriveKind(driveNumber); + if (kind != 0) return kind; // provider-backed (network) drive int blockDev = Fs::FsProbe::GetBlockDeviceForDrive(driveNumber); if (blockDev < 0) return 0; auto* dev = Drivers::Storage::GetBlockDevice(blockDev); diff --git a/kernel/src/Api/Storage.hpp b/kernel/src/Api/Storage.hpp index 52a8871..6f984a2 100644 --- a/kernel/src/Api/Storage.hpp +++ b/kernel/src/Api/Storage.hpp @@ -77,8 +77,10 @@ namespace montauk::abi { Fs::Vfs::VfsDriveLabel(v.drive, v.label, sizeof(v.label)); Fs::Vfs::VfsDriveFsType(v.drive, v.fsType, sizeof(v.fsType)); + v.kind = (uint32_t)Fs::Vfs::VfsDriveKind(v.drive); + v.partIndex = Fs::FsProbe::GetPartitionForDrive(v.drive); - if (v.partIndex < 0) continue; // ramdisk: no backing partition + if (v.partIndex < 0) continue; // ramdisk / network: no backing partition auto* part = Drivers::Storage::Gpt::GetPartition(v.partIndex); if (part == nullptr) continue; diff --git a/kernel/src/Api/Syscall.cpp b/kernel/src/Api/Syscall.cpp index 56629c9..3ce32c4 100644 --- a/kernel/src/Api/Syscall.cpp +++ b/kernel/src/Api/Syscall.cpp @@ -39,6 +39,7 @@ #include "CrashReportSyscall.hpp" // SYS_CRASH_REPORT #include "Clipboard.hpp" // SYS_CLIPBOARD_* (text and multi-format) #include "UserMemory.hpp" +#include "UserFsSyscall.hpp" // SYS_USERFS_MOUNT, SYS_USERFS_RECV, SYS_USERFS_REPLY, SYS_USERFS_UNMOUNT, SYS_USERFS_INFO namespace montauk::abi { @@ -456,6 +457,26 @@ namespace montauk::abi { case SYS_FS_SYNC: if (!Sched::Consent::Require(CAP_STORAGE_ADMIN)) return CapabilityDenied; return Sys_FsSync(); + case SYS_USERFS_MOUNT: + if (!UserMemory::Readable(frame->arg1)) return BadPointer; + return Sys_UserFsMount((const UserFsMountParams*)frame->arg1); + case SYS_USERFS_RECV: + if (!UserMemory::Writable(frame->arg2)) return BadPointer; + if (frame->arg4 > 0x1000000ULL) return InvalidArgument; + if (!UserMemory::Range(frame->arg3, frame->arg4, true)) return BadPointer; + return Sys_UserFsRecv((int)frame->arg1, (UserFsRequest*)frame->arg2, + (uint8_t*)frame->arg3, (uint32_t)frame->arg4, frame->arg5); + case SYS_USERFS_REPLY: + if (frame->arg5 > USERFS_MAX_DATA) return InvalidArgument; + if (frame->arg5 > 0 && !UserMemory::Range(frame->arg4, frame->arg5, false)) return BadPointer; + return Sys_UserFsReply((int)frame->arg1, frame->arg2, (int64_t)frame->arg3, + frame->arg5 > 0 ? (const uint8_t*)frame->arg4 : nullptr, + (uint32_t)frame->arg5); + case SYS_USERFS_UNMOUNT: + return Sys_UserFsUnmount((int)frame->arg1); + case SYS_USERFS_INFO: + if (!UserMemory::Writable(frame->arg2)) return BadPointer; + return Sys_UserFsInfo((int)frame->arg1, (UserFsInfo*)frame->arg2); case SYS_FS_GROW: if (!Sched::Consent::Require(CAP_STORAGE_ADMIN)) return CapabilityDenied; if (!UserMemory::Range(frame->arg2, sizeof(FsGrowStatus), true)) return BadPointer; diff --git a/kernel/src/Api/Syscall.hpp b/kernel/src/Api/Syscall.hpp index 9fe7c93..b437a85 100644 --- a/kernel/src/Api/Syscall.hpp +++ b/kernel/src/Api/Syscall.hpp @@ -408,6 +408,17 @@ namespace montauk::abi { /* Time.hpp -- wall clock as UTC unix seconds (SYS_GETTIME is local time). */ static constexpr uint64_t SYS_GETUNIXTIME = 209; // () -> seconds + /* UserFsSyscall.hpp -- userspace filesystem providers. A provider process + mounts a drive and then serves the VFS calls other processes make on it: + it receives each as a UserFsRequest and answers with a result and + optional data. The drive disappears when the provider unmounts or exits. + Used by smbfs.elf to expose SMB shares as ordinary drives. */ + static constexpr uint64_t SYS_USERFS_MOUNT = 210; // (const UserFsMountParams*) -> drive / status + static constexpr uint64_t SYS_USERFS_RECV = 211; // (drive, UserFsRequest*, data, dataMax, timeoutMs) -> 1 / 0 / status + static constexpr uint64_t SYS_USERFS_REPLY = 212; // (drive, id, result, data, len) -> status + static constexpr uint64_t SYS_USERFS_UNMOUNT = 213; // (drive) -> status; non-providers request an eject + static constexpr uint64_t SYS_USERFS_INFO = 214; // (drive, UserFsInfo*) -> status + /* Kernel-owned process capabilities. User identities may namespace per-user resources, but never participate in authorization decisions. */ static constexpr uint64_t CAP_PROCESS_ADMIN = 1ULL << 0; @@ -974,7 +985,7 @@ namespace montauk::abi { int32_t drive; // VFS drive number ("N:/") int32_t blockDev; // backing block device index, -1 if none int32_t partIndex; // global GPT partition index, -1 if none - uint32_t kind; // BlockDeviceKind: 0=none/ramdisk, 1=SATA, 2=SATAPI, 3=NVMe, 4=USB MSC + uint32_t kind; // BlockDeviceKind: 0=none/ramdisk, 1=SATA, 2=SATAPI, 3=NVMe, 4=USB MSC, 5=SD, 6=network (DRIVE_KIND_NETWORK) uint64_t startLba; // partition start LBA, 0 if none uint64_t sectorCount; // partition length in sectors, 0 if none uint32_t sectorSize; // logical sector size in bytes, 0 if none @@ -1013,6 +1024,67 @@ namespace montauk::abi { uint32_t stepsTotal; }; + /* ---- Userspace filesystem providers (SYS_USERFS_*) ---- */ + + /* VolInfo::kind / SYS_DRIVEKIND value of a provider-backed drive. */ + static constexpr uint32_t DRIVE_KIND_NETWORK = 6; + + /* Largest data payload of one request or reply. The kernel splits larger + reads and writes; SYS_USERFS_RECV needs a buffer at least this big. */ + static constexpr uint32_t USERFS_MAX_DATA = 65536; + + /* UserFsRequest::op. Unless noted, the provider replies with result >= 0 + on success or a negative StatusCodes value. */ + static constexpr uint32_t USERFS_OP_OPEN = 1; // path -> provider file handle (>= 0) + static constexpr uint32_t USERFS_OP_CREATE = 2; // path (create or truncate) -> provider file handle + static constexpr uint32_t USERFS_OP_CLOSE = 3; // handle; no reply expected (id == 0) + static constexpr uint32_t USERFS_OP_READ = 4; // handle, offset, size -> bytes read, reply data + static constexpr uint32_t USERFS_OP_WRITE = 5; // handle, offset, size, request data -> bytes written + static constexpr uint32_t USERFS_OP_GETSIZE = 6; // handle -> size in bytes + static constexpr uint32_t USERFS_OP_READDIR = 7; // path, offset = first index, size = max entries + // -> count; reply data = NUL-terminated names, + // directories with a trailing '/' + static constexpr uint32_t USERFS_OP_STAT = 8; // path -> 0, reply data = FileStat + static constexpr uint32_t USERFS_OP_DELETE = 9; // path (file or empty directory) + static constexpr uint32_t USERFS_OP_MKDIR = 10; // path + static constexpr uint32_t USERFS_OP_RENAME = 11; // path -> path2 + static constexpr uint32_t USERFS_OP_SETTIMES = 12; // path, atime, mtime + static constexpr uint32_t USERFS_OP_UNMOUNT = 13; // eject requested: flush, then unmount or exit; no reply + + struct UserFsMountParams { + char label[36]; // volume label shown for the drive + char fsType[12]; // short type name, e.g. "smb" + char source[128]; // what is mounted, e.g. "smb://nas/media" + uint32_t flags; // USERFS_MOUNT_* + uint32_t _pad0; + }; + + static constexpr uint32_t USERFS_MOUNT_READONLY = 1u << 0; + + struct UserFsRequest { + uint64_t id; // pass back to SYS_USERFS_REPLY; 0 = no reply expected + uint32_t op; // USERFS_OP_* + int32_t handle; // provider file handle (CLOSE/READ/WRITE/GETSIZE) + uint64_t offset; + uint64_t size; + int64_t atime; + int64_t mtime; + uint32_t dataLen; // bytes of request data copied to the RECV buffer + uint32_t replyMax; // most reply data the kernel will accept + char path[256]; // drive-local path, starts with '/' + char path2[256]; + }; + + struct UserFsInfo { + int32_t drive; + int32_t providerPid; + uint32_t flags; + uint32_t _pad0; + char label[36]; + char fsType[12]; + char source[128]; + }; + struct ProcInfo { int32_t pid; int32_t parentPid; diff --git a/kernel/src/Api/UserFsSyscall.hpp b/kernel/src/Api/UserFsSyscall.hpp new file mode 100644 index 0000000..d3843f9 --- /dev/null +++ b/kernel/src/Api/UserFsSyscall.hpp @@ -0,0 +1,41 @@ +/* + * UserFsSyscall.hpp + * SYS_USERFS_* syscalls: userspace filesystem providers + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once + +#include + +#include "Syscall.hpp" + +namespace montauk::abi { + + static int64_t Sys_UserFsMount(const UserFsMountParams* params) { + // Copy first: the strings must be terminated and stable while parsed. + UserFsMountParams local = *params; + local.label[sizeof(local.label) - 1] = '\0'; + local.fsType[sizeof(local.fsType) - 1] = '\0'; + local.source[sizeof(local.source) - 1] = '\0'; + return Fs::UserFs::Mount(&local); + } + + static int64_t Sys_UserFsRecv(int drive, UserFsRequest* out, uint8_t* data, + uint32_t dataMax, uint64_t timeoutMs) { + return Fs::UserFs::Recv(drive, out, data, dataMax, timeoutMs); + } + + static int64_t Sys_UserFsReply(int drive, uint64_t id, int64_t result, + const uint8_t* data, uint32_t len) { + return Fs::UserFs::Reply(drive, id, result, data, len); + } + + static int64_t Sys_UserFsUnmount(int drive) { + return Fs::UserFs::Unmount(drive); + } + + static int64_t Sys_UserFsInfo(int drive, UserFsInfo* out) { + return Fs::UserFs::Info(drive, out); + } +} diff --git a/kernel/src/Fs/UserFs.cpp b/kernel/src/Fs/UserFs.cpp new file mode 100644 index 0000000..3c40dc7 --- /dev/null +++ b/kernel/src/Fs/UserFs.cpp @@ -0,0 +1,755 @@ +/* + * UserFs.cpp + * Userspace filesystem providers: VFS drives served by a process + * Copyright (c) 2026 Daniel Hammer +*/ + +#include "UserFs.hpp" +#include "Vfs.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Fs::UserFs { + + using montauk::abi::UserFsRequest; + using montauk::abi::UserFsMountParams; + using montauk::abi::UserFsInfo; + using montauk::abi::FileStat; + using montauk::abi::USERFS_MAX_DATA; + + // Requests that may be queued or in service per mount; further callers + // wait for a slot. + static constexpr int MaxRequests = 16; + // Handles whose close has not been delivered to the provider yet. + static constexpr int CloseRingSize = 128; + // Per-thread buffers holding the names of a thread's last ReadDir. + static constexpr int NameSlots = 8; + static constexpr uint32_t NameBufSize = 4096; + // How long a caller waits for the provider before giving up. Providers + // must bound their own network waits below this. + static constexpr uint64_t RequestTimeoutMs = 45000; + + enum ReqState : uint8_t { ReqFree = 0, ReqPending, ReqTaken, ReqDone }; + + struct MountState; + + // One mounting of a slot. It is the FsDriver's ctx, so a call that the + // VFS dispatched before an unmount still holds the instance it was + // dispatched to and can tell that it is dead, even after the slot has + // been mounted again by another provider. + struct Instance { + MountState* mount; + bool dead; + }; + + struct Request { + ReqState state; + // The provider side is copying to or from `data` outside the lock; the + // waiter may not release the slot (and its buffer) until this clears. + bool busy; + UserFsRequest hdr; + Instance* inst; // mounting the request was made on + int ownerPid; // process of the waiting caller + uint8_t* data; // bounce buffer, owned by the waiting caller + uint32_t dataCap; + uint32_t replyLen; + int64_t result; + }; + + struct NameBuf { + int tid; + uint8_t* page; + }; + + struct MountState { + kcp::Spinlock lock; + bool active; + Instance* current; // live instance while active, else null + bool ejectRequested; + int ownerPid; + int ownerSession; + int drive; + uint32_t flags; + char label[36]; + char fsType[12]; + char source[128]; + Vfs::FsDriver driver; + Request reqs[MaxRequests]; + uint64_t nextId; + int32_t closeRing[CloseRingSize]; + uint32_t closeHead; + uint32_t closeCount; + NameBuf names[NameSlots]; + uint32_t nameCursor; + // Wake object for callers waiting for a free request slot. + uint8_t slotWait; + }; + + static MountState g_mounts[MaxMounts]; + static kcp::Mutex g_mountsLock; + + // Instances of unmounted drives, freed once no dispatched call can still + // hold them (g_mountsLock). If the list is full an instance is leaked, + // which costs a few bytes and nothing else. + static constexpr int MaxRetired = 64; + static Instance* g_retired[MaxRetired]; + + static bool CurrentKilled() { + auto* thr = Sched::GetCurrentThreadPtr(); + return thr == nullptr || thr->killPending.load(std::memory_order_acquire); + } + + static void CopyStr(char* dst, const char* src, int max) { + int i = 0; + if (src != nullptr) { + for (; i < max - 1 && src[i]; i++) dst[i] = src[i]; + } + dst[i] = '\0'; + } + + static MountState* MountForDrive(int drive) { + if (drive < FirstDrive || drive >= FirstDrive + MaxMounts) return nullptr; + MountState* m = &g_mounts[drive - FirstDrive]; + return m->active ? m : nullptr; + } + + // ========================================================================== + // Caller side: queue a request and wait for the provider's answer + // ========================================================================== + + // Release a request slot the caller gave up on or has consumed. Waits out + // a provider-side copy in progress so the bounce buffer is not freed under it. + static void ReleaseSlot(MountState* m, Request* req) { + for (;;) { + m->lock.Acquire(); + if (!req->busy) break; + m->lock.Release(); + Arch::Pause(); + } + req->state = ReqFree; + req->hdr.id = 0; + req->inst = nullptr; + req->ownerPid = -1; + req->data = nullptr; + req->dataCap = 0; + m->lock.Release(); + Sched::WakeObjectWaiters(&m->slotWait); + } + + // Send one request and wait for its reply. `in`/`inLen` is request data + // (written to the provider), `out`/`outMax` receives reply data. Returns + // the provider's result, or a negative status if it could not be delivered. + static int64_t Call(Instance* inst, const UserFsRequest& proto, + const uint8_t* in, uint32_t inLen, + uint8_t* out, uint32_t outMax, uint32_t* outLen) { + MountState* m = inst->mount; + if (outLen != nullptr) *outLen = 0; + if (inst->dead) return NoDevice; + // The provider calling into its own drive would wait on itself. + int pid = Sched::GetCurrentPid(); + if (pid < 0 || pid == m->ownerPid) return Busy; + if (inLen > USERFS_MAX_DATA || outMax > USERFS_MAX_DATA) return InvalidArgument; + + uint32_t cap = inLen > outMax ? inLen : outMax; + uint8_t* bounce = nullptr; + if (cap > 0) { + bounce = new uint8_t[cap]; + if (bounce == nullptr) return OutOfMemory; + if (inLen > 0) memcpy(bounce, in, inLen); + } + + uint64_t deadline = Timekeeping::GetMilliseconds() + RequestTimeoutMs; + + // Claim a slot. + Request* req = nullptr; + for (;;) { + uint64_t observed = Sched::ObserveObjectWake(&m->slotWait); + m->lock.Acquire(); + if (!inst->dead) { + for (int i = 0; i < MaxRequests; i++) { + if (m->reqs[i].state != ReqFree || m->reqs[i].busy) continue; + req = &m->reqs[i]; + req->inst = inst; + req->ownerPid = pid; + req->hdr = proto; + req->hdr.id = ++m->nextId; + req->hdr.dataLen = inLen; + req->hdr.replyMax = outMax; + req->data = bounce; + req->dataCap = cap; + req->replyLen = 0; + req->result = GenericFailure; + req->state = ReqPending; + break; + } + } + bool active = !inst->dead; + m->lock.Release(); + if (req != nullptr) break; + + uint64_t now = Timekeeping::GetMilliseconds(); + if (!active || now >= deadline || CurrentKilled()) { + delete[] bounce; + return active ? TimedOut : NoDevice; + } + Sched::BlockOnObjectSince(&m->slotWait, 50, observed); + } + + Sched::WakeObjectWaiters(m); + + // Wait for the reply. + int64_t result = GenericFailure; + for (;;) { + uint64_t observed = Sched::ObserveObjectWake(req); + m->lock.Acquire(); + bool done = req->state == ReqDone; + bool active = !inst->dead; + m->lock.Release(); + + if (done) { + result = req->result; + uint32_t n = req->replyLen; + if (n > outMax) n = outMax; + if (n > 0 && out != nullptr) memcpy(out, bounce, n); + if (outLen != nullptr) *outLen = n; + break; + } + + uint64_t now = Timekeeping::GetMilliseconds(); + if (!active) { result = NoDevice; break; } + if (now >= deadline) { result = TimedOut; break; } + if (CurrentKilled()) { result = GenericFailure; break; } + + uint64_t wait = deadline - now; + if (wait > 250) wait = 250; + Sched::BlockOnObjectSince(req, wait, observed); + } + + ReleaseSlot(m, req); + delete[] bounce; + return result; + } + + static UserFsRequest MakeRequest(uint32_t op, const char* path) { + UserFsRequest r; + memset(&r, 0, sizeof(r)); + r.op = op; + r.handle = -1; + if (path != nullptr) { + // Drive-root references arrive as "" or "/"; providers always see '/'. + CopyStr(r.path, path[0] ? path : "/", sizeof(r.path)); + } + return r; + } + + // ========================================================================== + // FsDriver entry points + // ========================================================================== + + static int DrvOpen(void* ctx, const char* path) { + auto* inst = (Instance*)ctx; + int64_t r = Call(inst, MakeRequest(montauk::abi::USERFS_OP_OPEN, path), nullptr, 0, nullptr, 0, nullptr); + return (r >= 0 && r <= 0x7FFFFFFF) ? (int)r : -1; + } + + static int DrvCreate(void* ctx, const char* path) { + auto* inst = (Instance*)ctx; + int64_t r = Call(inst, MakeRequest(montauk::abi::USERFS_OP_CREATE, path), nullptr, 0, nullptr, 0, nullptr); + return (r >= 0 && r <= 0x7FFFFFFF) ? (int)r : -1; + } + + // Close never blocks: it runs during handle teardown, including on process + // exit. The handle is queued and delivered to the provider as a + // no-reply request ahead of anything else. + static void DrvClose(void* ctx, int handle) { + auto* inst = (Instance*)ctx; + MountState* m = inst->mount; + bool queued = false; + m->lock.Acquire(); + if (!inst->dead && m->closeCount < CloseRingSize) { + m->closeRing[(m->closeHead + m->closeCount) % CloseRingSize] = handle; + m->closeCount++; + queued = true; + } + m->lock.Release(); + if (queued) Sched::WakeObjectWaiters(m); + } + + static int DrvRead(void* ctx, int handle, uint8_t* buffer, uint64_t offset, uint64_t size) { + auto* inst = (Instance*)ctx; + if (size > 0x7FFFFFFFULL) size = 0x7FFFFFFFULL; + uint64_t done = 0; + while (done < size) { + uint32_t chunk = (size - done > USERFS_MAX_DATA) ? USERFS_MAX_DATA : (uint32_t)(size - done); + UserFsRequest r = MakeRequest(montauk::abi::USERFS_OP_READ, nullptr); + r.handle = handle; + r.offset = offset + done; + r.size = chunk; + uint32_t got = 0; + int64_t res = Call(inst, r, nullptr, 0, buffer + done, chunk, &got); + if (res < 0) return done > 0 ? (int)done : -1; + if ((uint64_t)res < got) got = (uint32_t)res; + done += got; + if (got < chunk) break; + } + return (int)done; + } + + static int DrvWrite(void* ctx, int handle, const uint8_t* buffer, uint64_t offset, uint64_t size) { + auto* inst = (Instance*)ctx; + if (size > 0x7FFFFFFFULL) size = 0x7FFFFFFFULL; + uint64_t done = 0; + while (done < size) { + uint32_t chunk = (size - done > USERFS_MAX_DATA) ? USERFS_MAX_DATA : (uint32_t)(size - done); + UserFsRequest r = MakeRequest(montauk::abi::USERFS_OP_WRITE, nullptr); + r.handle = handle; + r.offset = offset + done; + r.size = chunk; + int64_t res = Call(inst, r, buffer + done, chunk, nullptr, 0, nullptr); + if (res < 0) return done > 0 ? (int)done : -1; + uint32_t wrote = (uint64_t)res > chunk ? chunk : (uint32_t)res; + done += wrote; + if (wrote < chunk) break; + } + return (int)done; + } + + static uint64_t DrvGetSize(void* ctx, int handle) { + auto* inst = (Instance*)ctx; + UserFsRequest r = MakeRequest(montauk::abi::USERFS_OP_GETSIZE, nullptr); + r.handle = handle; + int64_t res = Call(inst, r, nullptr, 0, nullptr, 0, nullptr); + return res < 0 ? 0 : (uint64_t)res; + } + + // The VFS contract hands back pointers that outlive the driver call, so + // each calling thread gets a page that stays allocated for the life of the + // kernel; only its contents are replaced by that thread's next ReadDir. + static uint8_t* NameBufForCurrentThread(MountState* m) { + int tid = Sched::GetCurrentTid(); + m->lock.Acquire(); + NameBuf* slot = nullptr; + for (int i = 0; i < NameSlots; i++) { + if (m->names[i].page != nullptr && m->names[i].tid == tid) { slot = &m->names[i]; break; } + } + if (slot == nullptr) { + slot = &m->names[m->nameCursor % NameSlots]; + m->nameCursor++; + slot->tid = tid; + } + uint8_t* page = slot->page; + m->lock.Release(); + + if (page == nullptr) { + uint8_t* fresh = new uint8_t[NameBufSize]; + if (fresh == nullptr) return nullptr; + memset(fresh, 0, NameBufSize); + m->lock.Acquire(); + if (slot->page == nullptr) { + slot->page = fresh; + fresh = nullptr; + } + page = slot->page; + m->lock.Release(); + delete[] fresh; + } + return page; + } + + static int DrvReadDirAt(void* ctx, const char* path, const char** outNames, + int maxEntries, int startIndex) { + auto* inst = (Instance*)ctx; + if (maxEntries <= 0) return 0; + uint8_t* page = NameBufForCurrentThread(inst->mount); + if (page == nullptr) return -1; + + UserFsRequest r = MakeRequest(montauk::abi::USERFS_OP_READDIR, path); + r.offset = (uint64_t)startIndex; + r.size = (uint64_t)maxEntries; + uint32_t got = 0; + int64_t res = Call(inst, r, nullptr, 0, page, NameBufSize - 1, &got); + if (res < 0) return -1; + page[got] = '\0'; + page[NameBufSize - 1] = '\0'; + + int count = 0; + uint32_t pos = 0; + while (count < maxEntries && count < res && pos < got) { + const char* name = (const char*)page + pos; + uint32_t len = 0; + while (pos + len < got && page[pos + len] != '\0') len++; + if (len == 0) break; + outNames[count++] = name; + pos += len + 1; + } + return count; + } + + static int DrvReadDir(void* ctx, const char* path, const char** outNames, int maxEntries) { + return DrvReadDirAt(ctx, path, outNames, maxEntries, 0); + } + + static int DrvStat(void* ctx, const char* path, Vfs::StatInfo* out) { + auto* inst = (Instance*)ctx; + FileStat st; + memset(&st, 0, sizeof(st)); + uint32_t got = 0; + int64_t res = Call(inst, MakeRequest(montauk::abi::USERFS_OP_STAT, path), nullptr, 0, + (uint8_t*)&st, sizeof(st), &got); + if (res < 0 || got < sizeof(st)) return -1; + out->size = st.size; + out->mtime = st.mtime; + out->ctime = st.ctime; + out->atime = st.atime; + out->isDir = st.isDir != 0; + out->mode = st.mode != 0 ? st.mode + : (out->isDir ? (Vfs::ModeDir | 0755u) : (Vfs::ModeReg | 0644u)); + return 0; + } + + static int SimplePathOp(void* ctx, uint32_t op, const char* path, const char* path2 = nullptr) { + auto* inst = (Instance*)ctx; + UserFsRequest r = MakeRequest(op, path); + if (path2 != nullptr) CopyStr(r.path2, path2[0] ? path2 : "/", sizeof(r.path2)); + int64_t res = Call(inst, r, nullptr, 0, nullptr, 0, nullptr); + return res < 0 ? -1 : 0; + } + + static int DrvDelete(void* ctx, const char* path) { + return SimplePathOp(ctx, montauk::abi::USERFS_OP_DELETE, path); + } + + static int DrvMkdir(void* ctx, const char* path) { + return SimplePathOp(ctx, montauk::abi::USERFS_OP_MKDIR, path); + } + + static int DrvRename(void* ctx, const char* oldPath, const char* newPath) { + return SimplePathOp(ctx, montauk::abi::USERFS_OP_RENAME, oldPath, newPath); + } + + // FsDriver::SetTimes codes: -1 missing, -2 unsupported, -3 bad time, -4 I/O. + static int DrvSetTimes(void* ctx, const char* path, int64_t atime, int64_t mtime) { + auto* inst = (Instance*)ctx; + UserFsRequest r = MakeRequest(montauk::abi::USERFS_OP_SETTIMES, path); + r.atime = atime; + r.mtime = mtime; + int64_t res = Call(inst, r, nullptr, 0, nullptr, 0, nullptr); + if (res >= 0) return 0; + if (res == NoSuchPath || res == NotFound) return -1; + if (res == UnsupportedOp) return -2; + if (res == InvalidArgument) return -3; + return -4; + } + + static const char* DrvGetLabel(void* ctx) { return ((Instance*)ctx)->mount->label; } + static const char* DrvGetFsType(void* ctx) { return ((Instance*)ctx)->mount->fsType; } + + // ========================================================================== + // Mount lifecycle + // ========================================================================== + + static void Teardown(MountState* m) { + m->lock.Acquire(); + bool wasActive = m->active; + Instance* inst = m->current; + m->active = false; + m->current = nullptr; + if (inst != nullptr) inst->dead = true; + m->lock.Release(); + if (!wasActive) return; + + // Waiters notice the dead mount and release their own slots. + for (int i = 0; i < MaxRequests; i++) Sched::WakeObjectWaiters(&m->reqs[i]); + Sched::WakeObjectWaiters(&m->slotWait); + Sched::WakeObjectWaiters(m); + + Vfs::UnregisterDrive(m->drive); + + if (inst != nullptr) { + g_mountsLock.Acquire(); + for (int i = 0; i < MaxRetired; i++) { + if (g_retired[i] == nullptr) { g_retired[i] = inst; break; } + } + g_mountsLock.Release(); + } + } + + // Free retired instances no dispatched call can still be holding: a call + // pins its drive before it reads the driver's ctx, so once a drive's pin + // count has been zero after the unmount, only later mountings are in use. + // Caller holds g_mountsLock. + static void SweepRetired() { + for (int i = 0; i < MaxRetired; i++) { + Instance* inst = g_retired[i]; + if (inst == nullptr || Vfs::DrivePinCount(inst->mount->drive) != 0) continue; + g_retired[i] = nullptr; + delete inst; + } + } + + int Mount(const UserFsMountParams* params) { + if (params == nullptr) return InvalidArgument; + auto* proc = Sched::GetCurrentProcessPtr(); + if (proc == nullptr) return GenericFailure; + bool readOnly = (params->flags & montauk::abi::USERFS_MOUNT_READONLY) != 0; + + Instance* inst = new Instance{nullptr, false}; + if (inst == nullptr) return OutOfMemory; + + g_mountsLock.Acquire(); + SweepRetired(); + for (int i = 0; i < MaxMounts; i++) { + MountState* m = &g_mounts[i]; + int drive = FirstDrive + i; + if (m->active || Vfs::IsDriveRegistered(drive)) continue; + inst->mount = m; + + m->ejectRequested = false; + m->ownerPid = proc->pid; + m->ownerSession = proc->sessionId; + m->drive = drive; + m->flags = params->flags; + CopyStr(m->label, params->label, sizeof(m->label)); + CopyStr(m->fsType, params->fsType, sizeof(m->fsType)); + CopyStr(m->source, params->source, sizeof(m->source)); + m->closeHead = 0; + m->closeCount = 0; + + m->driver = Vfs::FsDriver{}; + m->driver.ctx = inst; + m->driver.Open = DrvOpen; + m->driver.Read = DrvRead; + m->driver.GetSize = DrvGetSize; + m->driver.Close = DrvClose; + m->driver.ReadDir = DrvReadDir; + m->driver.ReadDirAt = DrvReadDirAt; + m->driver.Stat = DrvStat; + m->driver.GetLabel = DrvGetLabel; + m->driver.GetFsType = DrvGetFsType; + if (!readOnly) { + m->driver.Write = DrvWrite; + m->driver.Create = DrvCreate; + m->driver.Delete = DrvDelete; + m->driver.Mkdir = DrvMkdir; + m->driver.Rename = DrvRename; + m->driver.SetTimes = DrvSetTimes; + } + m->driver.concurrent = true; + m->driver.kind = Vfs::DriveKindNetwork; + + m->lock.Acquire(); + m->current = inst; + m->active = true; + m->lock.Release(); + if (Vfs::RegisterDrive(drive, &m->driver) != 0) { + m->lock.Acquire(); + m->active = false; + m->current = nullptr; + m->lock.Release(); + continue; + } + g_mountsLock.Release(); + Kt::KernelLogStream(Kt::OK, "UserFs") << "Drive " << drive << " provided by pid " + << proc->pid << " (" << m->source << ")"; + return drive; + } + g_mountsLock.Release(); + delete inst; + return Busy; + } + + static MountState* MountForOwner(int drive) { + MountState* m = MountForDrive(drive); + if (m == nullptr) return nullptr; + return m->ownerPid == Sched::GetCurrentPid() ? m : nullptr; + } + + int Recv(int drive, UserFsRequest* out, uint8_t* data, uint32_t dataMax, uint64_t timeoutMs) { + if (out == nullptr) return InvalidArgument; + if (data == nullptr || dataMax < USERFS_MAX_DATA) return BufferTooSmall; + MountState* m = MountForOwner(drive); + if (m == nullptr) return NoDevice; + + uint64_t deadline = Timekeeping::GetMilliseconds() + timeoutMs; + for (;;) { + uint64_t observed = Sched::ObserveObjectWake(m); + + m->lock.Acquire(); + if (!m->active) { + m->lock.Release(); + return NoDevice; + } + + // Closes first: they free provider handles and expect no reply. + if (m->closeCount > 0) { + int32_t handle = m->closeRing[m->closeHead]; + m->closeHead = (m->closeHead + 1) % CloseRingSize; + m->closeCount--; + m->lock.Release(); + memset(out, 0, sizeof(*out)); + out->op = montauk::abi::USERFS_OP_CLOSE; + out->handle = handle; + return 1; + } + + // Oldest pending request. + Request* req = nullptr; + for (int i = 0; i < MaxRequests; i++) { + if (m->reqs[i].state != ReqPending || m->reqs[i].inst != m->current) continue; + if (req == nullptr || m->reqs[i].hdr.id < req->hdr.id) req = &m->reqs[i]; + } + if (req != nullptr) { + req->state = ReqTaken; + req->busy = true; + m->lock.Release(); + + *out = req->hdr; + if (req->hdr.dataLen > 0) memcpy(data, req->data, req->hdr.dataLen); + + m->lock.Acquire(); + req->busy = false; + m->lock.Release(); + return 1; + } + + if (m->ejectRequested) { + m->ejectRequested = false; + m->lock.Release(); + memset(out, 0, sizeof(*out)); + out->op = montauk::abi::USERFS_OP_UNMOUNT; + out->handle = -1; + return 1; + } + m->lock.Release(); + + uint64_t now = Timekeeping::GetMilliseconds(); + if (timeoutMs == 0 || now >= deadline) return 0; + if (CurrentKilled()) return GenericFailure; + Sched::BlockOnObjectSince(m, deadline - now, observed); + } + } + + int Reply(int drive, uint64_t id, int64_t result, const uint8_t* data, uint32_t len) { + if (id == 0) return InvalidArgument; + MountState* m = MountForOwner(drive); + if (m == nullptr) return NoDevice; + + m->lock.Acquire(); + Request* req = nullptr; + for (int i = 0; i < MaxRequests; i++) { + if (m->reqs[i].state == ReqTaken && !m->reqs[i].busy && m->reqs[i].hdr.id == id) { + req = &m->reqs[i]; + break; + } + } + if (req == nullptr) { + // The caller gave up (timeout, killed) before the answer arrived. + m->lock.Release(); + return NotFound; + } + if (len > req->hdr.replyMax) len = req->hdr.replyMax; + if (len > req->dataCap) len = req->dataCap; + if (data == nullptr) len = 0; + req->busy = true; + m->lock.Release(); + + if (len > 0) memcpy(req->data, data, len); + + m->lock.Acquire(); + req->replyLen = len; + req->result = result; + req->state = ReqDone; + req->busy = false; + m->lock.Release(); + + Sched::WakeObjectWaiters(req); + return Success; + } + + int Unmount(int drive) { + MountState* m = MountForDrive(drive); + if (m == nullptr) return NoDevice; + auto* proc = Sched::GetCurrentProcessPtr(); + if (proc == nullptr) return GenericFailure; + + if (proc->pid == m->ownerPid) { + Teardown(m); + return Success; + } + + if (proc->sessionId != m->ownerSession && + !Sched::HasCapability(montauk::abi::CAP_STORAGE_ADMIN)) { + return PermissionDenied; + } + m->lock.Acquire(); + m->ejectRequested = true; + m->lock.Release(); + Sched::WakeObjectWaiters(m); + return Success; + } + + int Info(int drive, UserFsInfo* out) { + if (out == nullptr) return InvalidArgument; + MountState* m = MountForDrive(drive); + if (m == nullptr) return NoDevice; + memset(out, 0, sizeof(*out)); + m->lock.Acquire(); + out->drive = m->drive; + out->providerPid = m->ownerPid; + out->flags = m->flags; + CopyStr(out->label, m->label, sizeof(out->label)); + CopyStr(out->fsType, m->fsType, sizeof(out->fsType)); + CopyStr(out->source, m->source, sizeof(out->source)); + m->lock.Release(); + return Success; + } + + // Process exit terminates threads that are blocked in a call on the spot, + // without unwinding them, so a request slot such a thread was waiting in + // (and its bounce buffer) has to be reclaimed here. All of the process's + // threads are gone by now, so nothing else frees these. + static void ReclaimSlotsOf(MountState* m, int pid) { + for (int i = 0; i < MaxRequests; i++) { + Request* req = &m->reqs[i]; + uint8_t* bounce = nullptr; + bool reclaimed = false; + for (;;) { + m->lock.Acquire(); + if (req->state == ReqFree || req->ownerPid != pid) break; + if (!req->busy) { + bounce = req->data; + req->state = ReqFree; + req->hdr.id = 0; + req->inst = nullptr; + req->ownerPid = -1; + req->data = nullptr; + req->dataCap = 0; + reclaimed = true; + break; + } + m->lock.Release(); + Arch::Pause(); + } + m->lock.Release(); + if (reclaimed) { + delete[] bounce; + Sched::WakeObjectWaiters(&m->slotWait); + } + } + } + + void OnProcessExit(int pid) { + for (int i = 0; i < MaxMounts; i++) { + MountState* m = &g_mounts[i]; + if (m->active && m->ownerPid == pid) Teardown(m); + ReclaimSlotsOf(m, pid); + } + } + +} diff --git a/kernel/src/Fs/UserFs.hpp b/kernel/src/Fs/UserFs.hpp new file mode 100644 index 0000000..3851c96 --- /dev/null +++ b/kernel/src/Fs/UserFs.hpp @@ -0,0 +1,44 @@ +/* + * UserFs.hpp + * Userspace filesystem providers: VFS drives served by a process + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once +#include +#include + +// A provider process mounts a drive (Mount) and then serves it: every VFS call +// another process makes on that drive is queued as a UserFsRequest, the caller +// blocks, the provider picks the request up (Recv), does the work in userspace +// and answers (Reply). This keeps network protocols, their parsers and their +// credentials out of the kernel; smbfs.elf uses it to expose SMB shares. +// +// The drive is registered with FsDriver::concurrent set, so the VFS does not +// hold its local-driver lock while a caller waits on the provider. +namespace Fs::UserFs { + + // Provider-backed drives occupy the fixed drive range + // [FirstDrive, FirstDrive + MaxMounts), clear of disk partitions. + static constexpr int MaxMounts = 16; + static constexpr int FirstDrive = 32; + + // Returns the new drive number or a negative StatusCodes value. + int Mount(const montauk::abi::UserFsMountParams* params); + + // Provider side. Recv returns 1 with a request, 0 on timeout (timeoutMs 0 + // polls), or a negative status; `data` must hold USERFS_MAX_DATA bytes. + int Recv(int drive, montauk::abi::UserFsRequest* out, uint8_t* data, + uint32_t dataMax, uint64_t timeoutMs); + int Reply(int drive, uint64_t id, int64_t result, const uint8_t* data, uint32_t len); + + // The provider unmounts at once. Another process in the provider's session + // (or a storage administrator) asks the provider to eject instead. + int Unmount(int drive); + + int Info(int drive, montauk::abi::UserFsInfo* out); + + // Unmount every drive the exiting process was providing. + void OnProcessExit(int pid); + +} diff --git a/kernel/src/Fs/Vfs.cpp b/kernel/src/Fs/Vfs.cpp index 28a0931..2f6ba5c 100644 --- a/kernel/src/Fs/Vfs.cpp +++ b/kernel/src/Fs/Vfs.cpp @@ -7,6 +7,7 @@ #include "Vfs.hpp" #include #include +#include namespace Fs::Vfs { @@ -15,9 +16,44 @@ namespace Fs::Vfs { static uint32_t driveGeneration[MaxDrives]; static bool initialized = false; - // Protects driver dispatch from concurrent CPU access. Hot-unplug only - // flips driveActive so an interrupted dispatch never sees a null driver. - static kcp::Mutex vfsLock; + // Calls in flight per drive slot. A dispatch pins its drive (under + // tableLock) for the duration of the driver call, so UnregisterDrive can + // tell when nothing is still inside a driver it is about to free. + static uint32_t driveRefs[MaxDrives]; + + // Protects the drive table, generations and pin counts. Never held across + // a driver call. + static kcp::Mutex tableLock; + + // Serializes every call into the ordinary (non-concurrent) drivers, which + // share block devices and scratch state and rely on one call at a time. + // Drivers that set FsDriver::concurrent (network / userspace filesystems) + // are dispatched outside it: their calls block on a remote peer, and a + // stalled server must not freeze the local disks. + static kcp::Mutex localLock; + + // A pinned driver: valid between Pin* and Unpin. + struct Pinned { + FsDriver* driver = nullptr; + int drive = -1; + }; + + static void EnterDriver(Pinned& pin, int drive, FsDriver* driver) { + driveRefs[drive]++; + pin.driver = driver; + pin.drive = drive; + tableLock.Release(); + if (!driver->concurrent) localLock.Acquire(); + } + + static void Unpin(Pinned& pin) { + if (pin.driver == nullptr) return; + if (!pin.driver->concurrent) localLock.Release(); + tableLock.Acquire(); + driveRefs[pin.drive]--; + tableLock.Release(); + pin.driver = nullptr; + } // Upper bound on digits in a drive number. Without it the accumulator in // ParsePath overflows on a long digit run and wraps into a valid drive -- @@ -50,8 +86,8 @@ namespace Fs::Vfs { } // Resolve a drive number to its driver, or nullptr if the slot is out of - // range, unregistered, or empty. Caller must hold vfsLock: the returned - // pointer is only valid for as long as the lock is held. + // range, unregistered, or empty. Caller must hold tableLock; to call into + // the driver, pin it (PinDrive / PinFile) instead. static FsDriver* DriverForLocked(int driveNumber) { if (driveNumber < 0 || driveNumber >= MaxDrives) return nullptr; if (!driveActive[driveNumber]) return nullptr; @@ -77,8 +113,35 @@ namespace Fs::Vfs { } } + // Pin the driver of a drive for one call. Returns false (nothing pinned) + // when the drive is not mounted. outGeneration, when given, receives the + // generation the pin was taken under. + static bool PinDrive(int driveNumber, Pinned& pin, uint32_t* outGeneration = nullptr) { + tableLock.Acquire(); + FsDriver* driver = DriverForLocked(driveNumber); + if (driver == nullptr) { + tableLock.Release(); + return false; + } + if (outGeneration != nullptr) *outGeneration = driveGeneration[driveNumber]; + EnterDriver(pin, driveNumber, driver); + return true; + } + + static bool PinFile(const BackendFile& file, Pinned& pin) { + tableLock.Acquire(); + FsDriver* driver = DriverForFileLocked(file); + if (driver == nullptr) { + tableLock.Release(); + return false; + } + EnterDriver(pin, file.driveNumber, driver); + return true; + } + void Initialize() { for (int i = 0; i < MaxDrives; i++) { + driveRefs[i] = 0; driveTable[i] = nullptr; driveActive[i] = false; driveGeneration[i] = 1; @@ -97,15 +160,15 @@ namespace Fs::Vfs { if (driver == nullptr) return -1; if (!initialized) return -1; - vfsLock.Acquire(); + tableLock.Acquire(); if (driveActive[driveNumber]) { - vfsLock.Release(); + tableLock.Release(); return -1; } driveTable[driveNumber] = driver; BumpDriveGeneration(driveNumber); driveActive[driveNumber] = true; - vfsLock.Release(); + tableLock.Release(); Kt::KernelLogStream(Kt::OK, "VFS") << "Registered drive " << driveNumber; return 0; @@ -115,23 +178,32 @@ namespace Fs::Vfs { if (!initialized) return -1; if (driveNumber < 0 || driveNumber >= MaxDrives) return -1; - vfsLock.Acquire(); + tableLock.Acquire(); if (!driveActive[driveNumber]) { - vfsLock.Release(); + tableLock.Release(); return -1; } driveActive[driveNumber] = false; FsDriver* driver = driveTable[driveNumber]; driveTable[driveNumber] = nullptr; BumpDriveGeneration(driveNumber); + tableLock.Release(); - // Safe to tear down here: every dispatch path runs under vfsLock, so - // holding it means no call into this driver can still be in flight. - // Unmount frees the FsDriver itself, so nothing may touch it after. + // Unmount frees the FsDriver itself, so wait until every call that + // pinned it before the slot was deactivated has returned. Such calls + // are bounded local I/O (concurrent drivers own their storage and + // leave Unmount null), so this is a short spin, as the old single + // dispatch lock was. if (driver != nullptr && driver->Unmount != nullptr) { + for (;;) { + tableLock.Acquire(); + uint32_t refs = driveRefs[driveNumber]; + tableLock.Release(); + if (refs == 0) break; + Arch::Pause(); + } driver->Unmount(driver->ctx); } - vfsLock.Release(); Kt::KernelLogStream(Kt::OK, "VFS") << "Unregistered drive " << driveNumber; return 0; @@ -139,25 +211,33 @@ namespace Fs::Vfs { bool IsDriveRegistered(int driveNumber) { if (driveNumber < 0 || driveNumber >= MaxDrives) return false; - vfsLock.Acquire(); + tableLock.Acquire(); bool registered = driveActive[driveNumber]; - vfsLock.Release(); + tableLock.Release(); return registered; } + uint32_t DrivePinCount(int driveNumber) { + if (driveNumber < 0 || driveNumber >= MaxDrives) return 0; + tableLock.Acquire(); + uint32_t refs = driveRefs[driveNumber]; + tableLock.Release(); + return refs; + } + int FindLowestAvailableDrive(int firstDrive) { if (!initialized) return -1; if (firstDrive < 0) firstDrive = 0; - vfsLock.Acquire(); + tableLock.Acquire(); for (int i = firstDrive; i < MaxDrives; i++) { if (!driveActive[i]) { - vfsLock.Release(); + tableLock.Release(); return i; } } - vfsLock.Release(); + tableLock.Release(); return -1; } @@ -171,15 +251,12 @@ namespace Fs::Vfs { if (!ParsePath(path, drive, localPath)) return -1; - vfsLock.Acquire(); - FsDriver* driver = DriverForLocked(drive); - if (driver == nullptr || driver->Open == nullptr) { - vfsLock.Release(); - return -1; - } - uint32_t generation = driveGeneration[drive]; - int localHandle = driver->Open(driver->ctx, localPath); - vfsLock.Release(); + Pinned pin; + uint32_t generation = 0; + if (!PinDrive(drive, pin, &generation)) return -1; + FsDriver* driver = pin.driver; + int localHandle = (driver->Open != nullptr) ? driver->Open(driver->ctx, localPath) : -1; + Unpin(pin); if (localHandle < 0) return -1; outFile.driveNumber = drive; @@ -189,46 +266,42 @@ namespace Fs::Vfs { } int ReadBackendFile(const BackendFile& file, uint8_t* buffer, uint64_t offset, uint64_t size) { - vfsLock.Acquire(); - FsDriver* driver = DriverForFileLocked(file); - if (driver == nullptr || driver->Read == nullptr) { - vfsLock.Release(); - return -1; - } - - int result = driver->Read(driver->ctx, file.localHandle, buffer, offset, size); - vfsLock.Release(); + Pinned pin; + if (!PinFile(file, pin)) return -1; + FsDriver* driver = pin.driver; + int result = (driver->Read != nullptr) + ? driver->Read(driver->ctx, file.localHandle, buffer, offset, size) + : -1; + Unpin(pin); return result; } uint64_t GetBackendFileSize(const BackendFile& file) { - vfsLock.Acquire(); - FsDriver* driver = DriverForFileLocked(file); - if (driver == nullptr || driver->GetSize == nullptr) { - vfsLock.Release(); - return 0; - } - - uint64_t result = driver->GetSize(driver->ctx, file.localHandle); - vfsLock.Release(); + Pinned pin; + if (!PinFile(file, pin)) return 0; + FsDriver* driver = pin.driver; + uint64_t result = (driver->GetSize != nullptr) + ? driver->GetSize(driver->ctx, file.localHandle) + : 0; + Unpin(pin); return result; } bool BackendFileCanWrite(const BackendFile& file) { - vfsLock.Acquire(); + tableLock.Acquire(); FsDriver* driver = DriverForFileLocked(file); bool canWrite = driver != nullptr && driver->Write != nullptr; - vfsLock.Release(); + tableLock.Release(); return canWrite; } void CloseBackendFile(BackendFile& file) { - vfsLock.Acquire(); - FsDriver* driver = DriverForFileLocked(file); - if (driver != nullptr && driver->Close != nullptr) { - driver->Close(driver->ctx, file.localHandle); + Pinned pin; + if (PinFile(file, pin)) { + FsDriver* driver = pin.driver; + if (driver->Close != nullptr) driver->Close(driver->ctx, file.localHandle); + Unpin(pin); } - vfsLock.Release(); file.driveNumber = -1; file.localHandle = -1; @@ -236,15 +309,13 @@ namespace Fs::Vfs { } int WriteBackendFile(const BackendFile& file, const uint8_t* buffer, uint64_t offset, uint64_t size) { - vfsLock.Acquire(); - FsDriver* driver = DriverForFileLocked(file); - if (driver == nullptr || driver->Write == nullptr) { - vfsLock.Release(); - return -1; - } - - int result = driver->Write(driver->ctx, file.localHandle, buffer, offset, size); - vfsLock.Release(); + Pinned pin; + if (!PinFile(file, pin)) return -1; + FsDriver* driver = pin.driver; + int result = (driver->Write != nullptr) + ? driver->Write(driver->ctx, file.localHandle, buffer, offset, size) + : -1; + Unpin(pin); return result; } @@ -258,15 +329,12 @@ namespace Fs::Vfs { if (!ParsePath(path, drive, localPath)) return -1; - vfsLock.Acquire(); - FsDriver* driver = DriverForLocked(drive); - if (driver == nullptr || driver->Create == nullptr) { - vfsLock.Release(); - return -1; - } - uint32_t generation = driveGeneration[drive]; - int localHandle = driver->Create(driver->ctx, localPath); - vfsLock.Release(); + Pinned pin; + uint32_t generation = 0; + if (!PinDrive(drive, pin, &generation)) return -1; + FsDriver* driver = pin.driver; + int localHandle = (driver->Create != nullptr) ? driver->Create(driver->ctx, localPath) : -1; + Unpin(pin); if (localHandle < 0) return -1; outFile.driveNumber = drive; @@ -281,12 +349,13 @@ namespace Fs::Vfs { if (!ParsePath(path, drive, localPath)) return -1; - vfsLock.Acquire(); - FsDriver* driver = DriverForLocked(drive); - int result = (driver != nullptr && driver->Delete != nullptr) + Pinned pin; + if (!PinDrive(drive, pin)) return -1; + FsDriver* driver = pin.driver; + int result = (driver->Delete != nullptr) ? driver->Delete(driver->ctx, localPath) : -1; - vfsLock.Release(); + Unpin(pin); return result; } @@ -298,12 +367,13 @@ namespace Fs::Vfs { if (!ParsePath(path, drive, localPath)) return -1; - vfsLock.Acquire(); - FsDriver* driver = DriverForLocked(drive); - int result = (driver != nullptr && driver->Stat != nullptr) + Pinned pin; + if (!PinDrive(drive, pin)) return -1; + FsDriver* driver = pin.driver; + int result = (driver->Stat != nullptr) ? driver->Stat(driver->ctx, localPath, &out) : -1; - vfsLock.Release(); + Unpin(pin); return result; } @@ -313,12 +383,13 @@ namespace Fs::Vfs { if (!ParsePath(path, drive, localPath)) return -1; - vfsLock.Acquire(); - FsDriver* driver = DriverForLocked(drive); - int result = (driver != nullptr && driver->SetTimes != nullptr) + Pinned pin; + if (!PinDrive(drive, pin)) return -2; + FsDriver* driver = pin.driver; + int result = (driver->SetTimes != nullptr) ? driver->SetTimes(driver->ctx, localPath, atime, mtime) : -2; - vfsLock.Release(); + Unpin(pin); return result; } @@ -328,26 +399,27 @@ namespace Fs::Vfs { if (!ParsePath(path, drive, localPath)) return -1; - vfsLock.Acquire(); - FsDriver* driver = DriverForLocked(drive); - int result = (driver != nullptr && driver->Mkdir != nullptr) + Pinned pin; + if (!PinDrive(drive, pin)) return -1; + FsDriver* driver = pin.driver; + int result = (driver->Mkdir != nullptr) ? driver->Mkdir(driver->ctx, localPath) : -1; - vfsLock.Release(); + Unpin(pin); return result; } int VfsDriveList(int* outDrives, int maxEntries) { if (outDrives == nullptr || maxEntries <= 0) return 0; - vfsLock.Acquire(); + tableLock.Acquire(); int count = 0; for (int i = 0; i < MaxDrives && count < maxEntries; i++) { if (driveActive[i]) { outDrives[count++] = i; } } - vfsLock.Release(); + tableLock.Release(); return count; } static int CopyDriveString(int driveNumber, const char* (*FsDriver::*hook)(void*), @@ -355,21 +427,18 @@ namespace Fs::Vfs { if (out == nullptr || maxLen <= 0) return -1; out[0] = '\0'; - vfsLock.Acquire(); - FsDriver* driver = DriverForLocked(driveNumber); - if (driver == nullptr) { - vfsLock.Release(); - return -1; - } + Pinned pin; + if (!PinDrive(driveNumber, pin)) return -1; + FsDriver* driver = pin.driver; if (driver->*hook == nullptr) { - vfsLock.Release(); + Unpin(pin); return 0; } const char* value = (driver->*hook)(driver->ctx); if (value == nullptr || value[0] == '\0') { - vfsLock.Release(); + Unpin(pin); return 0; } @@ -380,10 +449,18 @@ namespace Fs::Vfs { } out[copied] = '\0'; - vfsLock.Release(); + Unpin(pin); return copied; } + int VfsDriveKind(int driveNumber) { + tableLock.Acquire(); + FsDriver* driver = DriverForLocked(driveNumber); + int kind = driver != nullptr ? (int)driver->kind : 0; + tableLock.Release(); + return kind; + } + int VfsDriveLabel(int driveNumber, char* outLabel, int maxLen) { return CopyDriveString(driveNumber, &FsDriver::GetLabel, outLabel, maxLen); } @@ -393,12 +470,13 @@ namespace Fs::Vfs { } int VfsGrow(int driveNumber, uint64_t partSectors, bool apply, GrowStatus* out) { - vfsLock.Acquire(); - FsDriver* driver = DriverForLocked(driveNumber); - int result = (driver != nullptr && driver->Grow != nullptr) + Pinned pin; + if (!PinDrive(driveNumber, pin)) return -2; + FsDriver* driver = pin.driver; + int result = (driver->Grow != nullptr) ? driver->Grow(driver->ctx, partSectors, apply, out) : -2; - vfsLock.Release(); + Unpin(pin); return result; } @@ -413,12 +491,13 @@ namespace Fs::Vfs { // Cross-drive rename not supported if (oldDrive != newDrive) return -1; - vfsLock.Acquire(); - FsDriver* driver = DriverForLocked(oldDrive); - int result = (driver != nullptr && driver->Rename != nullptr) + Pinned pin; + if (!PinDrive(oldDrive, pin)) return -1; + FsDriver* driver = pin.driver; + int result = (driver->Rename != nullptr) ? driver->Rename(driver->ctx, oldLocal, newLocal) : -1; - vfsLock.Release(); + Unpin(pin); return result; } @@ -433,12 +512,11 @@ namespace Fs::Vfs { if (startIndex < 0) return -1; if (!ParsePath(path, drive, localPath)) return -1; - vfsLock.Acquire(); - FsDriver* driver = DriverForLocked(drive); + Pinned pin; + if (!PinDrive(drive, pin)) return -1; + FsDriver* driver = pin.driver; int result; - if (driver == nullptr) { - result = -1; - } else if (driver->ReadDirAt) { + if (driver->ReadDirAt) { result = driver->ReadDirAt(driver->ctx, localPath, outNames, maxEntries, startIndex); } else if (driver->ReadDir) { // Driver without pagination support: only the first page is reachable. @@ -446,7 +524,7 @@ namespace Fs::Vfs { } else { result = -1; } - vfsLock.Release(); + Unpin(pin); return result; } diff --git a/kernel/src/Fs/Vfs.hpp b/kernel/src/Fs/Vfs.hpp index 380416c..ba53efe 100644 --- a/kernel/src/Fs/Vfs.hpp +++ b/kernel/src/Fs/Vfs.hpp @@ -93,13 +93,30 @@ namespace Fs::Vfs { // -1 is an I/O error, -2 a layout the driver cannot grow. Callers loop, // so other I/O interleaves between slices. int (*Grow)(void* ctx, uint64_t partSectors, bool apply, GrowStatus* out); + // True for drivers whose calls block on a peer outside the kernel + // (userspace / network filesystems). The VFS dispatches them without + // its local-driver lock, so several calls may be inside the driver at + // once and it must do its own locking. Such drivers own their storage: + // they leave Unmount null and must tolerate calls that were already + // dispatched when the drive was unregistered. + bool concurrent = false; + // DriveKind* override for drives with no backing block device + // (0 = derive the kind from the block device, as before). + uint8_t kind = 0; }; + // Drive kind reported for network / userspace-provided drives. Continues + // the BlockDeviceKind numbering used by SYS_DRIVEKIND and VolInfo::kind. + static constexpr uint8_t DriveKindNetwork = 6; + void Initialize(); bool IsInitialized(); int RegisterDrive(int driveNumber, FsDriver* driver); int UnregisterDrive(int driveNumber); bool IsDriveRegistered(int driveNumber); + // Calls currently dispatched on a drive slot, including calls that went + // to a driver since unregistered from it and have not returned yet. + uint32_t DrivePinCount(int driveNumber); int FindLowestAvailableDrive(int firstDrive = 0); int OpenBackendFile(const char* path, BackendFile& outFile); @@ -120,6 +137,8 @@ namespace Fs::Vfs { // Returns number of registered drives, fills outDrives[] with their indices int VfsDriveList(int* outDrives, int maxEntries); + // FsDriver::kind of a mounted drive, 0 if unset or not mounted. + int VfsDriveKind(int driveNumber); int VfsDriveLabel(int driveNumber, char* outLabel, int maxLen); int VfsDriveFsType(int driveNumber, char* outType, int maxLen); diff --git a/kernel/src/Sched/Scheduler.cpp b/kernel/src/Sched/Scheduler.cpp index a726b5a..4ec9723 100644 --- a/kernel/src/Sched/Scheduler.cpp +++ b/kernel/src/Sched/Scheduler.cpp @@ -32,6 +32,7 @@ #include #include #include +#include namespace Sched { @@ -1631,6 +1632,10 @@ namespace Sched { // exits without calling usb_close(). Drivers::USB::UserUsb::ReleaseAllForPid(exitingPid); + // Unmount drives this process was providing (userspace filesystems) + // before its handles go, so callers blocked on it fail at once. + Fs::UserFs::OnProcessExit(exitingPid); + // Release process-scoped IPC handles/mappings before tearing down the address space. Ipc::CleanupProcessSlot(slot, exitingPid, proc.pageTableRoot); montauk::abi::CleanupHeapForSlot(slot, proc.pageTableRoot); diff --git a/programs/GNUmakefile b/programs/GNUmakefile index 04136bc..2bdec3e 100644 --- a/programs/GNUmakefile +++ b/programs/GNUmakefile @@ -45,7 +45,7 @@ BINDIR := bin$(ARCH_SUFFIX) PROGRAMS := $(notdir $(wildcard src/*)) # Programs with custom Makefiles (built separately). -CUSTOM_BUILDS := 2048 files settings fetch wiki wikipedia weather imageviewer fontpreview spreadsheet wordprocessor pdfviewer disks devexplorer installer audio music video bluetooth network display capabilities keyboard about sshserver terminal syslog procmgr powermgr calculator charmap desktop login shell paint tcc lua screenshot texteditor mandelbrot printers timezone printd printctl dialogs libloader crashpad sshd rtlsdr sdr firstboot +CUSTOM_BUILDS := 2048 files settings fetch wiki wikipedia weather imageviewer fontpreview spreadsheet wordprocessor pdfviewer disks devexplorer installer audio music video bluetooth network display capabilities keyboard about sshserver terminal syslog procmgr powermgr calculator charmap desktop login shell paint tcc lua screenshot texteditor mandelbrot printers timezone printd printctl dialogs libloader crashpad sshd rtlsdr sdr firstboot smbfs smb SYSTEM_PROGRAMS := $(filter-out $(CUSTOM_BUILDS),$(PROGRAMS)) # Build targets: system programs go to bin/os/, apps go to bin/apps//. @@ -92,7 +92,7 @@ WPDIR := data/wallpapers WPSRC := $(wildcard $(WPDIR)/*.jpg) WPDST := $(patsubst $(WPDIR)/%,$(BINDIR)/os/wallpapers/%,$(WPSRC)) -.PHONY: all clean 2048 files settings fetch wiki wikipedia weather imageviewer fontpreview spreadsheet wordprocessor pdfviewer disks devexplorer installer audio music video bluetooth network display capabilities keyboard about sshserver sshd terminal syslog procmgr powermgr calculator charmap login desktop shell paint tcc lua screenshot texteditor mandelbrot printers timezone printd printctl dialogs icons fonts configs osdata bearssl libc tls libjpeg libjpegwrite install-apps libloader crashpad rtlsdr sdr check-syscalls gen-syscalls rust firstboot +.PHONY: all clean 2048 files settings fetch wiki wikipedia weather imageviewer fontpreview spreadsheet wordprocessor pdfviewer disks devexplorer installer audio music video bluetooth network display capabilities keyboard about sshserver sshd terminal syslog procmgr powermgr calculator charmap login desktop shell paint tcc lua screenshot texteditor mandelbrot printers timezone printd printctl dialogs icons fonts configs osdata bearssl libc tls libjpeg libjpegwrite install-apps libloader crashpad rtlsdr sdr check-syscalls gen-syscalls rust firstboot libsmb smbfs smb # The on-OS SDK, tcc (an x86 code generator) and the Rust programs exist # for x86_64 only. @@ -100,7 +100,7 @@ ifneq ($(ARCH),x86_64) ARCH_SKIP := devkit tcc rust endif -ALL_TARGETS := bearssl libc libjpeg libjpegwrite tls libloader rtlsdr sdr devkit $(TARGETS) files settings fetch wiki wikipedia weather imageviewer fontpreview spreadsheet wordprocessor pdfviewer disks devexplorer installer audio music video bluetooth network display capabilities sshserver terminal syslog procmgr powermgr calculator charmap 2048 paint tcc lua screenshot texteditor mandelbrot printers timezone printd printctl dialogs login desktop shell sshd icons fonts install-apps crashpad rust $(MANDST) $(WWWDST) $(CA_CERTS) $(CONFIGDST) $(OSDATADST) $(FWDST) $(LICDST) $(WPDST) +ALL_TARGETS := bearssl libc libjpeg libjpegwrite tls libsmb smbfs smb libloader rtlsdr sdr devkit $(TARGETS) files settings fetch wiki wikipedia weather imageviewer fontpreview spreadsheet wordprocessor pdfviewer disks devexplorer installer audio music video bluetooth network display capabilities sshserver terminal syslog procmgr powermgr calculator charmap 2048 paint tcc lua screenshot texteditor mandelbrot printers timezone printd printctl dialogs login desktop shell sshd icons fonts install-apps crashpad rust $(MANDST) $(WWWDST) $(CA_CERTS) $(CONFIGDST) $(OSDATADST) $(FWDST) $(LICDST) $(WPDST) # The Raspberry Pi SD image's first-boot program (built outside bin/, see # src/firstboot/Makefile); the SD image is aarch64 only. @@ -154,6 +154,17 @@ libc: $(LIBC_OUTPUTS) tls: bearssl libc $(MAKE) -C lib/tls +# Build the SMB2/SMB3 client library, the smbfs mount daemon (a userspace +# filesystem provider) and the smb command-line tool. +libsmb: bearssl libc + $(MAKE) -C lib/smb + +smbfs: libsmb + $(MAKE) -C src/smbfs + +smb: libsmb + $(MAKE) -C src/smb + # Build the shared-library loader used by runtime GUI components. libloader: libc $(MAKE) -C src/libloader @@ -338,7 +349,7 @@ texteditor: libc libloader dialogs $(MAKE) -C src/texteditor # Build Files (file manager; shares the desktop's app headers). -files: libc bearssl libjpeg +files: libc bearssl libjpeg libsmb $(MAKE) -C src/files # Build Mandelbrot standalone GUI app (depends on libc). @@ -558,6 +569,9 @@ clean: $(MAKE) -C lib/libjpeg clean $(MAKE) -C lib/libjpegwrite clean $(MAKE) -C lib/tls clean + $(MAKE) -C lib/smb clean + $(MAKE) -C src/smbfs clean + $(MAKE) -C src/smb clean $(MAKE) -C src/fetch clean $(MAKE) -C src/login clean $(MAKE) -C src/firstboot clean diff --git a/programs/include/Api/Syscall.hpp b/programs/include/Api/Syscall.hpp index c2fa9d9..395cc42 100644 --- a/programs/include/Api/Syscall.hpp +++ b/programs/include/Api/Syscall.hpp @@ -320,6 +320,17 @@ namespace montauk::abi { /* Time.hpp -- wall clock as UTC unix seconds (SYS_GETTIME is local time). */ static constexpr uint64_t SYS_GETUNIXTIME = 209; // () -> seconds + /* UserFsSyscall.hpp -- userspace filesystem providers. A provider process + mounts a drive and then serves the VFS calls other processes make on it: + it receives each as a UserFsRequest and answers with a result and + optional data. The drive disappears when the provider unmounts or exits. + Used by smbfs.elf to expose SMB shares as ordinary drives. */ + static constexpr uint64_t SYS_USERFS_MOUNT = 210; // (const UserFsMountParams*) -> drive / status + static constexpr uint64_t SYS_USERFS_RECV = 211; // (drive, UserFsRequest*, data, dataMax, timeoutMs) -> 1 / 0 / status + static constexpr uint64_t SYS_USERFS_REPLY = 212; // (drive, id, result, data, len) -> status + static constexpr uint64_t SYS_USERFS_UNMOUNT = 213; // (drive) -> status; non-providers request an eject + static constexpr uint64_t SYS_USERFS_INFO = 214; // (drive, UserFsInfo*) -> status + /* Kernel-owned process capabilities. User identities may namespace per-user resources, but never participate in authorization decisions. */ static constexpr uint64_t CAP_PROCESS_ADMIN = 1ULL << 0; @@ -897,7 +908,7 @@ namespace montauk::abi { int32_t drive; // VFS drive number ("N:/") int32_t blockDev; // backing block device index, -1 if none int32_t partIndex; // global GPT partition index, -1 if none - uint32_t kind; // BlockDeviceKind: 0=none/ramdisk, 1=SATA, 2=SATAPI, 3=NVMe, 4=USB MSC + uint32_t kind; // BlockDeviceKind: 0=none/ramdisk, 1=SATA, 2=SATAPI, 3=NVMe, 4=USB MSC, 5=SD, 6=network (DRIVE_KIND_NETWORK) uint64_t startLba; // partition start LBA, 0 if none uint64_t sectorCount; // partition length in sectors, 0 if none uint32_t sectorSize; // logical sector size in bytes, 0 if none @@ -936,6 +947,67 @@ namespace montauk::abi { uint32_t stepsTotal; }; + /* ---- Userspace filesystem providers (SYS_USERFS_*) ---- */ + + /* VolInfo::kind / SYS_DRIVEKIND value of a provider-backed drive. */ + static constexpr uint32_t DRIVE_KIND_NETWORK = 6; + + /* Largest data payload of one request or reply. The kernel splits larger + reads and writes; SYS_USERFS_RECV needs a buffer at least this big. */ + static constexpr uint32_t USERFS_MAX_DATA = 65536; + + /* UserFsRequest::op. Unless noted, the provider replies with result >= 0 + on success or a negative StatusCodes value. */ + static constexpr uint32_t USERFS_OP_OPEN = 1; // path -> provider file handle (>= 0) + static constexpr uint32_t USERFS_OP_CREATE = 2; // path (create or truncate) -> provider file handle + static constexpr uint32_t USERFS_OP_CLOSE = 3; // handle; no reply expected (id == 0) + static constexpr uint32_t USERFS_OP_READ = 4; // handle, offset, size -> bytes read, reply data + static constexpr uint32_t USERFS_OP_WRITE = 5; // handle, offset, size, request data -> bytes written + static constexpr uint32_t USERFS_OP_GETSIZE = 6; // handle -> size in bytes + static constexpr uint32_t USERFS_OP_READDIR = 7; // path, offset = first index, size = max entries + // -> count; reply data = NUL-terminated names, + // directories with a trailing '/' + static constexpr uint32_t USERFS_OP_STAT = 8; // path -> 0, reply data = FileStat + static constexpr uint32_t USERFS_OP_DELETE = 9; // path (file or empty directory) + static constexpr uint32_t USERFS_OP_MKDIR = 10; // path + static constexpr uint32_t USERFS_OP_RENAME = 11; // path -> path2 + static constexpr uint32_t USERFS_OP_SETTIMES = 12; // path, atime, mtime + static constexpr uint32_t USERFS_OP_UNMOUNT = 13; // eject requested: flush, then unmount or exit; no reply + + struct UserFsMountParams { + char label[36]; // volume label shown for the drive + char fsType[12]; // short type name, e.g. "smb" + char source[128]; // what is mounted, e.g. "smb://nas/media" + uint32_t flags; // USERFS_MOUNT_* + uint32_t _pad0; + }; + + static constexpr uint32_t USERFS_MOUNT_READONLY = 1u << 0; + + struct UserFsRequest { + uint64_t id; // pass back to SYS_USERFS_REPLY; 0 = no reply expected + uint32_t op; // USERFS_OP_* + int32_t handle; // provider file handle (CLOSE/READ/WRITE/GETSIZE) + uint64_t offset; + uint64_t size; + int64_t atime; + int64_t mtime; + uint32_t dataLen; // bytes of request data copied to the RECV buffer + uint32_t replyMax; // most reply data the kernel will accept + char path[256]; // drive-local path, starts with '/' + char path2[256]; + }; + + struct UserFsInfo { + int32_t drive; + int32_t providerPid; + uint32_t flags; + uint32_t _pad0; + char label[36]; + char fsType[12]; + char source[128]; + }; + // Bluetooth scan result (returned by SYS_BTSCAN) struct BtScanResult { uint8_t bdAddr[6]; diff --git a/programs/include/libc/montauk.h b/programs/include/libc/montauk.h index 28403b8..30a6734 100644 --- a/programs/include/libc/montauk.h +++ b/programs/include/libc/montauk.h @@ -233,6 +233,11 @@ extern "C" { #define MTK_SYS_WIN_DRAG_GET_DATA 207 #define MTK_SYS_FS_GROW 208 #define MTK_SYS_GETUNIXTIME 209 +#define MTK_SYS_USERFS_MOUNT 210 +#define MTK_SYS_USERFS_RECV 211 +#define MTK_SYS_USERFS_REPLY 212 +#define MTK_SYS_USERFS_UNMOUNT 213 +#define MTK_SYS_USERFS_INFO 214 /* @SYSCALLS-END */ /* Syscall status codes (montauk/statuscodes.h for C++). */ diff --git a/programs/include/montauk/syscall.h b/programs/include/montauk/syscall.h index 09694d1..d9d1512 100644 --- a/programs/include/montauk/syscall.h +++ b/programs/include/montauk/syscall.h @@ -664,6 +664,33 @@ namespace montauk { return (int)syscall3(montauk::abi::SYS_FS_GROW, (uint64_t)drive, (uint64_t)status, apply ? 1 : 0); } + // ---- Userspace filesystem providers (see Api/Syscall.hpp) ---- + // Mount a provider-backed drive served by the calling process. Returns the + // drive number or a negative status. + inline int userfs_mount(const montauk::abi::UserFsMountParams* params) { + return (int)syscall1(montauk::abi::SYS_USERFS_MOUNT, (uint64_t)params); + } + // Wait up to timeoutMs for the next request on `drive`. `data` receives the + // request payload and must hold USERFS_MAX_DATA bytes. Returns 1 with a + // request, 0 on timeout, or a negative status. + inline int userfs_recv(int drive, montauk::abi::UserFsRequest* req, void* data, + uint32_t dataMax, uint64_t timeoutMs) { + return (int)syscall5(montauk::abi::SYS_USERFS_RECV, (uint64_t)drive, (uint64_t)req, + (uint64_t)data, dataMax, timeoutMs); + } + inline int userfs_reply(int drive, uint64_t id, int64_t result, + const void* data = nullptr, uint32_t len = 0) { + return (int)syscall5(montauk::abi::SYS_USERFS_REPLY, (uint64_t)drive, id, + (uint64_t)result, (uint64_t)data, len); + } + // The provider unmounts its drive at once; any other process in the same + // session asks the provider to eject (it sees USERFS_OP_UNMOUNT). + inline int userfs_unmount(int drive) { + return (int)syscall1(montauk::abi::SYS_USERFS_UNMOUNT, (uint64_t)drive); + } + inline int userfs_info(int drive, montauk::abi::UserFsInfo* out) { + return (int)syscall2(montauk::abi::SYS_USERFS_INFO, (uint64_t)drive, (uint64_t)out); + } inline int fs_format(const montauk::abi::FsFormatParams* params) { return (int)syscall1(montauk::abi::SYS_FSFORMAT, (uint64_t)params); } diff --git a/programs/include/smb/montauk.hpp b/programs/include/smb/montauk.hpp new file mode 100644 index 0000000..540d7c8 --- /dev/null +++ b/programs/include/smb/montauk.hpp @@ -0,0 +1,23 @@ +/* + * montauk.hpp + * MontaukOS transport for the SMB client library + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once +#include + +namespace smb { + + // A TCP connection to an SMB server, usable as the library's Io. + struct MontaukLink { + int fd; + }; + + // Resolve `host` (name or dotted address) and connect to `port` (0 = 445). + // Returns OK, ERR_NOT_FOUND if the name does not resolve, or ERR_IO. + int link_open(MontaukLink* link, const char* host, int port); + void link_close(MontaukLink* link); + Io link_io(MontaukLink* link); + +} diff --git a/programs/include/smb/mount.hpp b/programs/include/smb/mount.hpp new file mode 100644 index 0000000..6bbf007 --- /dev/null +++ b/programs/include/smb/mount.hpp @@ -0,0 +1,158 @@ +/* + * mount.hpp + * Launching and managing smbfs mounts from other programs + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once +#include +#include +#include +#include + +// Shares are mounted by the smbfs.elf provider process (src/smbfs). These +// helpers start one without blocking the caller -- a GUI polls the job from +// its event loop -- and find or eject the drives that are already mounted. +namespace smb { + + struct MountRequest { + const char* host; + const char* share; + const char* user; // "" or null for a guest logon + const char* domain; + const char* password; + const char* label; // "" or null for the default "share on host" + int port; // 0 = 445 + bool readOnly; + }; + + struct MountJob { + int pid; // smbfs process, -1 when idle + uint64_t started; + char line[200]; + int lineLen; + }; + + // How long smbfs gets to report success or failure. + static constexpr uint64_t MOUNT_TIMEOUT_MS = 60000; + + // Characters that would break smbfs's argument splitting. + inline bool mount_arg_ok(const char* s) { + if (s == nullptr) return true; + for (; *s; s++) { + if (*s == '"' || (unsigned char)*s < 0x20) return false; + } + return true; + } + + // Start mounting. Returns false if smbfs could not be launched or an + // argument contains characters that cannot be passed. + inline bool mount_begin(MountJob* job, const MountRequest& rq) { + job->pid = -1; + job->lineLen = 0; + if (rq.host == nullptr || rq.share == nullptr || !rq.host[0] || !rq.share[0]) return false; + if (!mount_arg_ok(rq.host) || !mount_arg_ok(rq.share) || !mount_arg_ok(rq.user) || + !mount_arg_ok(rq.domain) || !mount_arg_ok(rq.label)) return false; + + char args[900]; + int n = snprintf(args, sizeof(args), "\"//%s/%s\"", rq.host, rq.share); + if (rq.user && rq.user[0]) n += snprintf(args + n, sizeof(args) - (size_t)n, " --user \"%s\"", rq.user); + if (rq.domain && rq.domain[0]) n += snprintf(args + n, sizeof(args) - (size_t)n, " --domain \"%s\"", rq.domain); + if (rq.label && rq.label[0]) n += snprintf(args + n, sizeof(args) - (size_t)n, " --label \"%s\"", rq.label); + if (rq.port > 0) n += snprintf(args + n, sizeof(args) - (size_t)n, " --port %d", rq.port); + if (rq.readOnly) n += snprintf(args + n, sizeof(args) - (size_t)n, " --ro"); + if (n >= (int)sizeof(args) - 1) return false; + + // The child inherits this process's environment at spawn, which is + // how the password reaches it without appearing in its arguments. + setenv("SMB_PASSWORD", rq.password ? rq.password : "", 1); + int pid = montauk::spawn_redir("0:/os/smbfs.elf", args); + unsetenv("SMB_PASSWORD"); + if (pid < 0) return false; + + job->pid = pid; + job->started = montauk::get_milliseconds(); + return true; + } + + // Poll a job started with mount_begin. Returns 0 while still mounting, + // 1 once mounted (*drive is the drive number), or -1 on failure with a + // message in `error` and smbfs's smb::Status in *status. + inline int mount_poll(MountJob* job, int* drive, int* status, char* error, int errorMax) { + if (job->pid < 0) return -1; + char buf[128]; + int n; + while ((n = montauk::childio_read(job->pid, buf, sizeof(buf))) > 0) { + for (int i = 0; i < n; i++) { + if (buf[i] != '\n') { + if (buf[i] != '\r' && job->lineLen < (int)sizeof(job->line) - 1) + job->line[job->lineLen++] = buf[i]; + continue; + } + job->line[job->lineLen] = '\0'; + job->lineLen = 0; + if (!strncmp(job->line, "OK ", 3)) { + if (drive) *drive = atoi(job->line + 3); + job->pid = -1; + return 1; + } + if (!strncmp(job->line, "ERR ", 4)) { + const char* p = job->line + 4; + if (status) *status = atoi(p); + while (*p && *p != ' ') p++; + while (*p == ' ') p++; + if (error && errorMax > 0) snprintf(error, (size_t)errorMax, "%s", p); + job->pid = -1; + return -1; + } + } + } + // A negative read means the process is gone without having answered. + bool timedOut = montauk::get_milliseconds() - job->started > MOUNT_TIMEOUT_MS; + if (n < 0 || timedOut) { + if (timedOut) montauk::kill(job->pid); + if (status) *status = -1; + if (error && errorMax > 0) + snprintf(error, (size_t)errorMax, "%s", timedOut ? "the server did not respond" + : "the mount helper stopped unexpectedly"); + job->pid = -1; + return -1; + } + return 0; + } + + // Give up on a mount in progress. + inline void mount_cancel(MountJob* job) { + if (job->pid >= 0) montauk::kill(job->pid); + job->pid = -1; + } + + // Find the drive an "smb://host/share" source is mounted on, or -1. + // Host and share compare without regard to case. + inline int find_mount(const char* host, const char* share) { + char want[160]; + snprintf(want, sizeof(want), "smb://%s/%s", host, share); + int drives[64]; + int n = montauk::drivelist(drives, 64); + for (int i = 0; i < n; i++) { + montauk::abi::UserFsInfo info; + if (montauk::userfs_info(drives[i], &info) != 0) continue; + const char* a = info.source; + const char* b = want; + for (; *a && *b; a++, b++) { + char ca = (*a >= 'A' && *a <= 'Z') ? (char)(*a + 32) : *a; + char cb = (*b >= 'A' && *b <= 'Z') ? (char)(*b + 32) : *b; + if (ca != cb) break; + } + if (*a == '\0' && *b == '\0') return drives[i]; + } + return -1; + } + + // Ask the provider of `drive` to disconnect and exit. Returns 0 if the + // request was delivered; the drive disappears shortly afterwards. + inline int unmount(int drive) { + return montauk::userfs_unmount(drive); + } + +} diff --git a/programs/include/smb/smb.hpp b/programs/include/smb/smb.hpp new file mode 100644 index 0000000..b3a52ec --- /dev/null +++ b/programs/include/smb/smb.hpp @@ -0,0 +1,213 @@ +/* + * smb.hpp + * SMB2/SMB3 client library + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once +#include +#include + +// A small blocking SMB client: one TCP connection, one session, one request +// in flight. It speaks SMB 2.0.2, 2.1, 3.0 and 3.0.2 with NTLMv2 +// authentication (inside SPNEGO) and message signing; no SMB1, no Kerberos, +// no SMB3 encryption (a server or share that demands encryption is refused +// with ERR_UNSUPPORTED). +// +// The library does no I/O of its own. The caller supplies a connected byte +// stream and a random source through smb::Io, which keeps it portable: the +// same sources build for MontaukOS (smbfs.elf, smb.elf) and for the host test +// harness in tests/smb. It needs malloc/free, and BearSSL's hash, +// HMAC and AES primitives. +// +// Paths are UTF-8 and relative to the share root; '/' and '\' both separate +// components and a leading separator is ignored ("" is the share root). +// Times are UTC unix seconds. +namespace smb { + + enum Status : int { + OK = 0, + ERR_IO = -1, // connection lost or could not send/receive + ERR_TIMEOUT = -2, // server did not answer in time + ERR_PROTOCOL = -3, // malformed or unexpected server message + ERR_AUTH = -4, // logon refused (bad user or password) + ERR_ACCESS = -5, // access denied + ERR_NOT_FOUND = -6, // no such file or directory + ERR_EXISTS = -7, // name already exists + ERR_NOT_EMPTY = -8, // directory not empty + ERR_IS_DIR = -9, + ERR_NOT_DIR = -10, + ERR_BUSY = -11, // sharing violation / file in use + ERR_NO_SPACE = -12, + ERR_UNSUPPORTED = -13, // server needs something this client lacks + ERR_BAD_SHARE = -14, // no such share on the server + ERR_NOMEM = -15, + ERR_INVALID = -16, // invalid argument or name + ERR_SIGNATURE = -17, // a signed server message failed verification + ERR_READ_ONLY = -18, + ERR_FAILED = -19 // any other server error (see last_nt_status) + }; + + // Short English description of a Status, for messages and logs. + const char* status_text(int status); + + // Byte stream to the server plus a random source. + struct Io { + void* ctx; + // Send exactly `len` bytes. Returns 0, or -1 if the connection failed. + int (*send)(void* ctx, const void* data, uint32_t len); + // Receive up to `len` bytes, waiting at most timeoutMs for the first. + // Returns the count (> 0), 0 on timeout, or -1 if the connection closed. + int (*recv)(void* ctx, void* buf, uint32_t len, uint32_t timeoutMs); + // Fill `buf` with cryptographically random bytes. + void (*random)(void* ctx, void* buf, uint32_t len); + }; + + // An empty user logs on as guest, falling back to an anonymous session. + // `domain` may be empty. The strings are only read during connect(). + struct Credentials { + const char* user; + const char* password; + const char* domain; + }; + + struct FileId { + uint8_t raw[16]; + }; + + struct FileInfo { + uint64_t size; + int64_t mtime; + int64_t ctime; // creation time + int64_t atime; + uint32_t attributes; // ATTR_* + bool isDir; + }; + + static constexpr uint32_t ATTR_READONLY = 0x01; + static constexpr uint32_t ATTR_HIDDEN = 0x02; + static constexpr uint32_t ATTR_SYSTEM = 0x04; + static constexpr uint32_t ATTR_DIRECTORY = 0x10; + + struct DirEntry { + char name[768]; // UTF-8 + FileInfo info; + }; + + struct ShareInfo { + char name[256]; // UTF-8 + char comment[256]; + uint32_t type; // SHARE_TYPE_* in the low bits + bool hidden; // administrative / special share (C$, IPC$, ...) + }; + + static constexpr uint32_t SHARE_TYPE_DISK = 0; + static constexpr uint32_t SHARE_TYPE_PRINTER = 1; + static constexpr uint32_t SHARE_TYPE_DEVICE = 2; + static constexpr uint32_t SHARE_TYPE_IPC = 3; + + // How to open a file (open()). + enum OpenMode : int { + OPEN_READ = 0, // existing file, read only + OPEN_READWRITE, // existing file, read and write + OPEN_CREATE, // create or truncate, read and write + OPEN_CREATE_NEW // create, fail with ERR_EXISTS if present + }; + + // Largest read or write one request carries; larger calls are split. + static constexpr uint32_t MAX_IO = 65536; + + struct Client { + Io io; + bool connected; + uint16_t dialect; // 0x0202, 0x0210, 0x0300, 0x0302 + bool signing; // requests are signed, responses verified + bool guest; // logged on as guest or anonymously + uint8_t signingKey[16]; + uint64_t sessionId; + uint64_t messageId; + uint32_t maxRead; + uint32_t maxWrite; + uint32_t maxTransact; + uint32_t timeoutMs; // per-request answer timeout + uint32_t lastNtStatus; // NTSTATUS of the last failed request + char server[256]; // name used in \\server\share paths + uint8_t* buf; // message buffer (request, then response) + uint32_t bufCap; + uint32_t respLen; // length of the response held in buf + bool serverRequiresSigning; + }; + + // ---- Session ---- + + // Negotiate and log on over an already connected stream. `serverName` is + // the host name or address the user gave (used for share paths). On + // failure the client is left disconnected; call disconnect() regardless + // to free its buffer. + int connect(Client* c, const Io& io, const char* serverName, const Credentials& creds); + + // Log off (best effort) and free the client's buffer. The caller closes + // the underlying stream. + void disconnect(Client* c); + + // Round trip to the server; ERR_IO / ERR_TIMEOUT mean the link is dead. + int echo(Client* c); + + // ---- Shares ---- + + int tree_connect(Client* c, const char* share, uint32_t* outTreeId); + int tree_disconnect(Client* c, uint32_t treeId); + + // List the server's shares (srvsvc NetrShareEnum over IPC$). Returns the + // number written to `out` (at most `max`) or a negative Status. + int list_shares(Client* c, ShareInfo* out, int max); + + // ---- Files ---- + + int open(Client* c, uint32_t tree, const char* path, OpenMode mode, + FileId* outId, FileInfo* outInfo = nullptr); + int close(Client* c, uint32_t tree, const FileId& id); + + // Read / write up to `len` bytes at `offset`. Returns the byte count + // (0 at end of file) or a negative Status. + int read(Client* c, uint32_t tree, const FileId& id, uint64_t offset, void* buf, uint32_t len); + int write(Client* c, uint32_t tree, const FileId& id, uint64_t offset, const void* buf, uint32_t len); + + // Current size of an open file. + int file_size(Client* c, uint32_t tree, const FileId& id, uint64_t* outSize); + + // ---- Namespace ---- + + int stat(Client* c, uint32_t tree, const char* path, FileInfo* out); + + // Enumerate a directory ("." and ".." are skipped). The callback returns + // false to stop early. Returns the number of entries delivered or a + // negative Status. + typedef bool (*DirCallback)(void* ctx, const DirEntry& entry); + int list_dir(Client* c, uint32_t tree, const char* path, DirCallback cb, void* ctx); + + int mkdir(Client* c, uint32_t tree, const char* path); + // Remove a file or an empty directory. + int remove(Client* c, uint32_t tree, const char* path); + // Rename / move within the share. Fails with ERR_EXISTS if `to` exists + // unless `replace` is set. + int rename(Client* c, uint32_t tree, const char* from, const char* to, bool replace = false); + // Set access / modification times; a time of 0 is left unchanged. + int set_times(Client* c, uint32_t tree, const char* path, int64_t atime, int64_t mtime); + + // ---- Helpers shared with the tools ---- + + // Split "smb://[domain;]user@host[:port]/share/sub/dir" or + // "//host/share/sub" or "\\host\share" into its parts. Missing parts come + // back empty (port 0). Returns false if there is no host. + struct Url { + char host[256]; + char share[256]; + char path[512]; + char user[128]; + char domain[128]; + int port; + }; + bool parse_url(const char* text, Url* out); + +} diff --git a/programs/lib/smb/Makefile b/programs/lib/smb/Makefile new file mode 100644 index 0000000..c7e828e --- /dev/null +++ b/programs/lib/smb/Makefile @@ -0,0 +1,71 @@ +# Makefile for the SMB2/SMB3 client library on MontaukOS +# Copyright (c) 2026 Daniel Hammer + +MAKEFLAGS += -rR +.SUFFIXES: + +# ---- Toolchain ---- + +include ../../mk/arch.mk +ifneq ($(wildcard $(TOOLCHAIN_PREFIX)gcc),) + CXX := $(TOOLCHAIN_PREFIX)g++ + AR := $(TOOLCHAIN_PREFIX)ar +else + CXX := g++ + AR := ar +endif + +# ---- Paths ---- + +BEARSSL := ../bearssl +LIBC_INC := ../../include/libc +PROG_INC := ../../include +OBJDIR := obj$(ARCH_SUFFIX) + +# ---- Compiler flags ---- + +CXXFLAGS := \ + -std=gnu++20 \ + -g -O2 -pipe \ + -Wall \ + -Wextra \ + -Wno-unused-parameter \ + -nostdinc \ + -ffreestanding \ + -fno-stack-protector \ + -fno-stack-check \ + -fno-PIC \ + -fno-rtti \ + -fno-exceptions \ + -ffunction-sections \ + -fdata-sections \ + $(ARCH_CFLAGS) \ + $(ARCH_NOFP_FLAGS) \ + -I $(PROG_INC) \ + -isystem $(LIBC_INC) \ + -I $(BEARSSL)/inc \ + -isystem ../../../kernel/freestnd-c-hdrs/$(ARCH)/include \ + -isystem ../../../kernel/freestnd-cxx-hdrs/$(ARCH)/include + +# ---- Target ---- + +TARGET := $(ARCH_OUT)libsmb.a +SRCS := smb.cpp ntlm.cpp crypto.cpp montauk_io.cpp +OBJS := $(SRCS:%.cpp=$(OBJDIR)/%.o) +HDRS := internal.hpp $(PROG_INC)/smb/smb.hpp $(PROG_INC)/smb/montauk.hpp + +.PHONY: all clean + +all: $(TARGET) + +$(TARGET): $(OBJS) + @mkdir -p $(dir $@) + rm -f $@ + $(AR) rcs $@ $^ + +$(OBJDIR)/%.o: %.cpp $(HDRS) Makefile + @mkdir -p $(OBJDIR) + $(CXX) $(CXXFLAGS) -c $< -o $@ + +clean: + rm -rf $(OBJDIR) $(TARGET) diff --git a/programs/lib/smb/crypto.cpp b/programs/lib/smb/crypto.cpp new file mode 100644 index 0000000..8237fe9 --- /dev/null +++ b/programs/lib/smb/crypto.cpp @@ -0,0 +1,174 @@ +/* + * crypto.cpp + * Hashes and MACs used by SMB signing and NTLMv2 + * Copyright (c) 2026 Daniel Hammer +*/ + +#include "internal.hpp" + +extern "C" { +#include +#include +#include +} + +namespace smb::detail { + + // ========================================================================== + // MD4 (RFC 1320). BearSSL does not ship it; NTLM's password hash needs it. + // ========================================================================== + + static inline uint32_t rol(uint32_t v, int s) { return (v << s) | (v >> (32 - s)); } + + static void md4_block(uint32_t st[4], const uint8_t* blk) { + uint32_t x[16]; + for (int i = 0; i < 16; i++) x[i] = get32(blk + i * 4); + uint32_t a = st[0], b = st[1], c = st[2], d = st[3]; + + #define MD4_F(x, y, z) (((x) & (y)) | (~(x) & (z))) + #define MD4_G(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z))) + #define MD4_H(x, y, z) ((x) ^ (y) ^ (z)) + #define R1(a, b, c, d, k, s) a = rol(a + MD4_F(b, c, d) + x[k], s) + #define R2(a, b, c, d, k, s) a = rol(a + MD4_G(b, c, d) + x[k] + 0x5A827999u, s) + #define R3(a, b, c, d, k, s) a = rol(a + MD4_H(b, c, d) + x[k] + 0x6ED9EBA1u, s) + + for (int i = 0; i < 16; i += 4) { + R1(a, b, c, d, i, 3); R1(d, a, b, c, i + 1, 7); + R1(c, d, a, b, i + 2, 11); R1(b, c, d, a, i + 3, 19); + } + for (int i = 0; i < 4; i++) { + R2(a, b, c, d, i, 3); R2(d, a, b, c, i + 4, 5); + R2(c, d, a, b, i + 8, 9); R2(b, c, d, a, i + 12, 13); + } + static const int order[4] = {0, 2, 1, 3}; + for (int j = 0; j < 4; j++) { + int i = order[j]; + R3(a, b, c, d, i, 3); R3(d, a, b, c, i + 8, 9); + R3(c, d, a, b, i + 4, 11); R3(b, c, d, a, i + 12, 15); + } + + #undef MD4_F + #undef MD4_G + #undef MD4_H + #undef R1 + #undef R2 + #undef R3 + + st[0] += a; st[1] += b; st[2] += c; st[3] += d; + } + + void md4(const uint8_t* data, size_t len, uint8_t out[16]) { + uint32_t st[4] = {0x67452301u, 0xEFCDAB89u, 0x98BADCFEu, 0x10325476u}; + size_t off = 0; + for (; off + 64 <= len; off += 64) md4_block(st, data + off); + + uint8_t tail[128]; + size_t rem = len - off; + memset(tail, 0, sizeof(tail)); + if (rem > 0) memcpy(tail, data + off, rem); + tail[rem] = 0x80; + size_t total = (rem < 56) ? 64 : 128; + put64(tail + total - 8, (uint64_t)len * 8); + md4_block(st, tail); + if (total == 128) md4_block(st, tail + 64); + + for (int i = 0; i < 4; i++) put32(out + i * 4, st[i]); + } + + // ========================================================================== + // HMAC + // ========================================================================== + + static void hmac(const br_hash_class* cls, const uint8_t* key, size_t keyLen, + const uint8_t* a, size_t aLen, const uint8_t* b, size_t bLen, uint8_t* out) { + br_hmac_key_context kc; + br_hmac_context ctx; + br_hmac_key_init(&kc, cls, key, keyLen); + br_hmac_init(&ctx, &kc, 0); + if (aLen > 0) br_hmac_update(&ctx, a, aLen); + if (bLen > 0) br_hmac_update(&ctx, b, bLen); + br_hmac_out(&ctx, out); + } + + void hmac_md5(const uint8_t* key, size_t keyLen, const uint8_t* a, size_t aLen, + const uint8_t* b, size_t bLen, uint8_t out[16]) { + hmac(&br_md5_vtable, key, keyLen, a, aLen, b, bLen, out); + } + + void hmac_sha256(const uint8_t* key, size_t keyLen, const uint8_t* a, size_t aLen, + const uint8_t* b, size_t bLen, uint8_t out[32]) { + hmac(&br_sha256_vtable, key, keyLen, a, aLen, b, bLen, out); + } + + // ========================================================================== + // AES-128-CMAC (RFC 4493), the SMB 3.0 signing algorithm + // ========================================================================== + + // Double a 128-bit value in GF(2^128) (the CMAC subkey step). + static void cmac_double(const uint8_t in[16], uint8_t out[16]) { + uint8_t carry = 0; + for (int i = 15; i >= 0; i--) { + uint8_t next = (uint8_t)(in[i] >> 7); + out[i] = (uint8_t)((in[i] << 1) | carry); + carry = next; + } + if (carry) out[15] ^= 0x87; + } + + void aes_cmac(const uint8_t key[16], const uint8_t* data, size_t len, uint8_t out[16]) { + br_aes_ct_cbcenc_keys keys; + br_aes_ct_cbcenc_init(&keys, key, 16); + + // CBC-MAC is CBC encryption that keeps only the chaining value, which + // br_aes_ct_cbcenc_run leaves in `iv`. + uint8_t iv[16]; + uint8_t block[16]; + + uint8_t l[16], k1[16], k2[16]; + memset(iv, 0, 16); + memset(l, 0, 16); + br_aes_ct_cbcenc_run(&keys, iv, l, 16); + cmac_double(l, k1); + cmac_double(k1, k2); + + size_t blocks = (len + 15) / 16; + bool lastComplete = len > 0 && (len % 16) == 0; + if (blocks == 0) blocks = 1; + + memset(iv, 0, 16); + for (size_t i = 0; i + 1 < blocks; i++) { + memcpy(block, data + i * 16, 16); + br_aes_ct_cbcenc_run(&keys, iv, block, 16); + } + + const uint8_t* last = data + (blocks - 1) * 16; + if (lastComplete) { + for (int i = 0; i < 16; i++) block[i] = last[i] ^ k1[i]; + } else { + size_t rem = len - (blocks - 1) * 16; + memset(block, 0, 16); + if (rem > 0) memcpy(block, last, rem); + block[rem] = 0x80; + for (int i = 0; i < 16; i++) block[i] ^= k2[i]; + } + br_aes_ct_cbcenc_run(&keys, iv, block, 16); + memcpy(out, block, 16); + } + + void smb3_kdf(const uint8_t key[16], const char* label, size_t labelLen, + const char* context, size_t contextLen, uint8_t out[16]) { + // K(1) = HMAC-SHA256(key, [i=1]_32be | label | 0x00 | context | [L=128]_32be) + uint8_t msg[160]; + size_t n = 0; + if (labelLen + contextLen + 9 > sizeof(msg)) { memset(out, 0, 16); return; } + msg[n++] = 0; msg[n++] = 0; msg[n++] = 0; msg[n++] = 1; + memcpy(msg + n, label, labelLen); n += labelLen; + msg[n++] = 0; + memcpy(msg + n, context, contextLen); n += contextLen; + msg[n++] = 0; msg[n++] = 0; msg[n++] = 0; msg[n++] = 128; + uint8_t full[32]; + hmac_sha256(key, 16, msg, n, nullptr, 0, full); + memcpy(out, full, 16); + } + +} diff --git a/programs/lib/smb/internal.hpp b/programs/lib/smb/internal.hpp new file mode 100644 index 0000000..e09bc88 --- /dev/null +++ b/programs/lib/smb/internal.hpp @@ -0,0 +1,88 @@ +/* + * internal.hpp + * SMB client library internals: byte order, crypto, NTLM, SPNEGO + * Copyright (c) 2026 Daniel Hammer +*/ + +#pragma once +#include +#include + +namespace smb::detail { + + // ---- Little-endian accessors (the SMB wire format) ---- + + inline void put16(uint8_t* p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); } + inline void put32(uint8_t* p, uint32_t v) { + p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); + } + inline void put64(uint8_t* p, uint64_t v) { put32(p, (uint32_t)v); put32(p + 4, (uint32_t)(v >> 32)); } + inline uint16_t get16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); } + inline uint32_t get32(const uint8_t* p) { + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); + } + inline uint64_t get64(const uint8_t* p) { return (uint64_t)get32(p) | ((uint64_t)get32(p + 4) << 32); } + + // ---- Time ---- + + // Windows FILETIME: 100 ns ticks since 1601-01-01 UTC. + static constexpr uint64_t FILETIME_UNIX_EPOCH = 116444736000000000ULL; + inline int64_t filetime_to_unix(uint64_t ft) { + if (ft == 0) return 0; + if (ft < FILETIME_UNIX_EPOCH) return 0; + return (int64_t)((ft - FILETIME_UNIX_EPOCH) / 10000000ULL); + } + inline uint64_t unix_to_filetime(int64_t t) { + if (t <= 0) return 0; + return (uint64_t)t * 10000000ULL + FILETIME_UNIX_EPOCH; + } + + // ---- Text ---- + + // UTF-8 -> UTF-16LE. Returns the number of bytes written (no terminator), + // or -1 if `cap` is too small. With `path` set, '/' becomes '\' and + // leading / trailing / doubled separators are dropped. + int utf8_to_utf16(const char* in, uint8_t* out, uint32_t cap, bool path = false); + // UTF-16LE (`len` bytes) -> NUL-terminated UTF-8, truncated to fit `cap`. + void utf16_to_utf8(const uint8_t* in, uint32_t len, char* out, uint32_t cap); + + // ---- Crypto (crypto.cpp) ---- + + void md4(const uint8_t* data, size_t len, uint8_t out[16]); + // HMAC over the concatenation of two segments (either may be empty). + void hmac_md5(const uint8_t* key, size_t keyLen, const uint8_t* a, size_t aLen, + const uint8_t* b, size_t bLen, uint8_t out[16]); + void hmac_sha256(const uint8_t* key, size_t keyLen, const uint8_t* a, size_t aLen, + const uint8_t* b, size_t bLen, uint8_t out[32]); + void aes_cmac(const uint8_t key[16], const uint8_t* data, size_t len, uint8_t out[16]); + // SMB 3.0 key derivation (SP800-108 counter mode, HMAC-SHA256, 128 bits). + // label and context include their terminating NUL. + void smb3_kdf(const uint8_t key[16], const char* label, size_t labelLen, + const char* context, size_t contextLen, uint8_t out[16]); + + // ---- NTLMSSP + SPNEGO (ntlm.cpp) ---- + + static constexpr size_t NTLM_NEGOTIATE_LEN = 32; + void ntlm_negotiate(uint8_t out[NTLM_NEGOTIATE_LEN]); + + struct NtlmAuthParams { + const char* user; // "" with anonymous set + const char* password; + const char* domain; + bool anonymous; + uint8_t clientChallenge[8]; + uint64_t fallbackTime; // FILETIME used if the server sent no timestamp + }; + // Build the AUTHENTICATE message for a server CHALLENGE. Returns its + // length or a negative Status. sessionKey receives the 16-byte session + // base key (all zero for an anonymous logon). + int ntlm_authenticate(const uint8_t* challenge, size_t challengeLen, const NtlmAuthParams& p, + uint8_t* out, size_t outCap, uint8_t sessionKey[16]); + + // Wrap an NTLM token in a SPNEGO NegTokenInit (first leg) or NegTokenResp + // (later legs). Returns the blob length or -1 if it does not fit. + int spnego_wrap(const uint8_t* token, size_t tokenLen, bool first, uint8_t* out, size_t outCap); + // Find the NTLM token inside a server security blob (SPNEGO or raw). + bool spnego_unwrap(const uint8_t* blob, size_t len, const uint8_t** token, size_t* tokenLen); + +} diff --git a/programs/lib/smb/montauk_io.cpp b/programs/lib/smb/montauk_io.cpp new file mode 100644 index 0000000..4ac3238 --- /dev/null +++ b/programs/lib/smb/montauk_io.cpp @@ -0,0 +1,111 @@ +/* + * montauk_io.cpp + * MontaukOS transport for the SMB client library + * Copyright (c) 2026 Daniel Hammer +*/ + +#include +#include + +namespace smb { + + static constexpr uint64_t kSendStallMs = 15000; + + static bool parse_ipv4(const char* s, uint32_t* out) { + uint32_t parts[4] = {0, 0, 0, 0}; + int part = 0; + while (*s) { + if (part >= 4 || *s < '0' || *s > '9') return false; + uint32_t value = 0; + while (*s >= '0' && *s <= '9') { + value = value * 10u + (uint32_t)(*s - '0'); + if (value > 255u) return false; + s++; + } + parts[part++] = value; + if (*s == '.') { s++; continue; } + if (*s != '\0') return false; + } + if (part != 4) return false; + *out = parts[0] | (parts[1] << 8) | (parts[2] << 16) | (parts[3] << 24); + return true; + } + + int link_open(MontaukLink* link, const char* host, int port) { + link->fd = -1; + uint32_t ip = 0; + if (!parse_ipv4(host, &ip)) ip = montauk::resolve(host); + if (ip == 0) return ERR_NOT_FOUND; + + int fd = montauk::socket(montauk::abi::SOCK_TCP); + if (fd < 0) return ERR_IO; + if (montauk::connect(fd, ip, (uint16_t)(port > 0 ? port : 445)) < 0) { + montauk::closesocket(fd); + return ERR_IO; + } + link->fd = fd; + return OK; + } + + void link_close(MontaukLink* link) { + if (link->fd >= 0) montauk::closesocket(link->fd); + link->fd = -1; + } + + static int io_send(void* ctx, const void* data, uint32_t len) { + int fd = ((MontaukLink*)ctx)->fd; + if (fd < 0) return -1; + const uint8_t* p = (const uint8_t*)data; + uint32_t sent = 0; + uint64_t deadline = montauk::get_milliseconds() + kSendStallMs; + while (sent < len) { + int r = montauk::send(fd, p + sent, len - sent); + if (r > 0) { + sent += (uint32_t)r; + deadline = montauk::get_milliseconds() + kSendStallMs; + continue; + } + if (r < 0) return -1; + uint64_t now = montauk::get_milliseconds(); + if (now >= deadline) return -1; + uint32_t signals = montauk::wait_handle( + fd, montauk::abi::IPC_SIGNAL_WRITABLE | montauk::abi::IPC_SIGNAL_PEER_CLOSED, + deadline - now); + if (signals == (uint32_t)-1 || (signals & montauk::abi::IPC_SIGNAL_PEER_CLOSED)) return -1; + } + return 0; + } + + static int io_recv(void* ctx, void* buf, uint32_t len, uint32_t timeoutMs) { + int fd = ((MontaukLink*)ctx)->fd; + if (fd < 0) return -1; + uint64_t deadline = montauk::get_milliseconds() + timeoutMs; + for (;;) { + int r = montauk::recv(fd, buf, len); + if (r > 0) return r; + if (r < 0) return -1; + uint64_t now = montauk::get_milliseconds(); + if (now >= deadline) return 0; + uint32_t signals = montauk::wait_handle( + fd, montauk::abi::IPC_SIGNAL_READABLE | montauk::abi::IPC_SIGNAL_PEER_CLOSED, + deadline - now); + if (signals == (uint32_t)-1) return -1; + if ((signals & montauk::abi::IPC_SIGNAL_PEER_CLOSED) && + !(signals & montauk::abi::IPC_SIGNAL_READABLE)) return -1; + } + } + + static void io_random(void* ctx, void* buf, uint32_t len) { + montauk::getrandom(buf, len); + } + + Io link_io(MontaukLink* link) { + Io io; + io.ctx = link; + io.send = io_send; + io.recv = io_recv; + io.random = io_random; + return io; + } + +} diff --git a/programs/lib/smb/ntlm.cpp b/programs/lib/smb/ntlm.cpp new file mode 100644 index 0000000..b6a83dd --- /dev/null +++ b/programs/lib/smb/ntlm.cpp @@ -0,0 +1,283 @@ +/* + * ntlm.cpp + * NTLMv2 authentication messages and their SPNEGO wrapping + * Copyright (c) 2026 Daniel Hammer +*/ + +#include "internal.hpp" + +namespace smb::detail { + + static const uint8_t kSignature[8] = {'N', 'T', 'L', 'M', 'S', 'S', 'P', 0}; + + static constexpr uint32_t NTLMSSP_NEGOTIATE_UNICODE = 0x00000001; + static constexpr uint32_t NTLMSSP_REQUEST_TARGET = 0x00000004; + static constexpr uint32_t NTLMSSP_NEGOTIATE_SIGN = 0x00000010; + static constexpr uint32_t NTLMSSP_NEGOTIATE_NTLM = 0x00000200; + static constexpr uint32_t NTLMSSP_NEGOTIATE_ANONYMOUS = 0x00000800; + static constexpr uint32_t NTLMSSP_NEGOTIATE_ALWAYS_SIGN = 0x00008000; + static constexpr uint32_t NTLMSSP_NEGOTIATE_EXTENDED = 0x00080000; + static constexpr uint32_t NTLMSSP_NEGOTIATE_TARGET_INFO = 0x00800000; + static constexpr uint32_t NTLMSSP_NEGOTIATE_128 = 0x20000000; + static constexpr uint32_t NTLMSSP_NEGOTIATE_56 = 0x80000000; + + // No KEY_EXCH: the session key is then the session base key itself, with + // no RC4-wrapped random key to exchange. + static constexpr uint32_t kClientFlags = + NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_SIGN | + NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_ALWAYS_SIGN | NTLMSSP_NEGOTIATE_EXTENDED | + NTLMSSP_NEGOTIATE_TARGET_INFO | NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_56; + + static constexpr uint16_t MsvAvEOL = 0; + static constexpr uint16_t MsvAvTimestamp = 7; + + void ntlm_negotiate(uint8_t out[NTLM_NEGOTIATE_LEN]) { + memset(out, 0, NTLM_NEGOTIATE_LEN); + memcpy(out, kSignature, 8); + put32(out + 8, 1); + put32(out + 12, kClientFlags); + // Empty domain and workstation fields, both pointing past the header. + put32(out + 20, NTLM_NEGOTIATE_LEN); + put32(out + 28, NTLM_NEGOTIATE_LEN); + } + + // Uppercase a UTF-16LE string in place. NTLM uppercases the user name; + // ASCII and Latin-1 cover the names this client can be given sensibly. + static void utf16_upper(uint8_t* s, int len) { + for (int i = 0; i + 1 < len; i += 2) { + uint16_t ch = get16(s + i); + if (ch >= 'a' && ch <= 'z') ch = (uint16_t)(ch - 32); + else if (ch >= 0xE0 && ch <= 0xFE && ch != 0xF7) ch = (uint16_t)(ch - 32); + put16(s + i, ch); + } + } + + static void put_field(uint8_t* p, uint16_t len, uint32_t offset) { + put16(p, len); + put16(p + 2, len); + put32(p + 4, offset); + } + + int ntlm_authenticate(const uint8_t* challenge, size_t challengeLen, const NtlmAuthParams& p, + uint8_t* out, size_t outCap, uint8_t sessionKey[16]) { + static constexpr size_t kHeader = 64; + memset(sessionKey, 0, 16); + + if (challengeLen < 48 || memcmp(challenge, kSignature, 8) != 0 || get32(challenge + 8) != 2) + return ERR_PROTOCOL; + const uint8_t* serverChallenge = challenge + 24; + + // Target info: the AV pair list this response must echo. + uint16_t tiLen = get16(challenge + 40); + uint32_t tiOff = get32(challenge + 44); + const uint8_t* targetInfo = nullptr; + if (tiLen > 0) { + if ((size_t)tiOff + tiLen > challengeLen) return ERR_PROTOCOL; + targetInfo = challenge + tiOff; + } + bool haveTimestamp = false; + uint64_t timestamp = p.fallbackTime; + for (size_t pos = 0; pos + 4 <= tiLen;) { + uint16_t id = get16(targetInfo + pos); + uint16_t len = get16(targetInfo + pos + 2); + if (id == MsvAvEOL) break; + if (pos + 4 + len > tiLen) return ERR_PROTOCOL; + if (id == MsvAvTimestamp && len == 8) { + timestamp = get64(targetInfo + pos + 4); + haveTimestamp = true; + } + pos += 4 + (size_t)len; + } + + if (outCap < kHeader) return ERR_NOMEM; + memset(out, 0, kHeader); + memcpy(out, kSignature, 8); + put32(out + 8, 3); + + if (p.anonymous) { + // Null session: no user, no responses, no session key. + put_field(out + 12, 0, kHeader); + put_field(out + 20, 0, kHeader); + put_field(out + 28, 0, kHeader); + put_field(out + 36, 0, kHeader); + put_field(out + 44, 0, kHeader); + put_field(out + 52, 0, kHeader); + put32(out + 60, kClientFlags | NTLMSSP_NEGOTIATE_ANONYMOUS); + return (int)kHeader; + } + + uint8_t user16[512], domain16[512], pass16[1024]; + int userLen = utf8_to_utf16(p.user ? p.user : "", user16, sizeof(user16)); + int domainLen = utf8_to_utf16(p.domain ? p.domain : "", domain16, sizeof(domain16)); + int passLen = utf8_to_utf16(p.password ? p.password : "", pass16, sizeof(pass16)); + if (userLen < 0 || domainLen < 0 || passLen < 0) return ERR_INVALID; + + // NTOWFv2 = HMAC-MD5(MD4(password), UPPER(user) | domain) + uint8_t ntHash[16], ntowf[16]; + md4(pass16, (size_t)passLen, ntHash); + uint8_t upper[512]; + memcpy(upper, user16, (size_t)userLen); + utf16_upper(upper, userLen); + hmac_md5(ntHash, 16, upper, (size_t)userLen, domain16, (size_t)domainLen, ntowf); + memset(pass16, 0, sizeof(pass16)); + memset(ntHash, 0, sizeof(ntHash)); + + // The NTLMv2 blob ("temp"): version, timestamp, client challenge and + // the server's target info. + size_t tempLen = 28 + (size_t)tiLen + 4; + size_t ntRespLen = 16 + tempLen; + size_t total = kHeader + 24 + ntRespLen + (size_t)domainLen + (size_t)userLen; + if (total > outCap) return ERR_NOMEM; + + uint8_t* lm = out + kHeader; + uint8_t* nt = lm + 24; + uint8_t* temp = nt + 16; + memset(temp, 0, tempLen); + temp[0] = 1; + temp[1] = 1; + put64(temp + 8, timestamp); + memcpy(temp + 16, p.clientChallenge, 8); + if (tiLen > 0) memcpy(temp + 28, targetInfo, tiLen); + + // NTProofStr = HMAC-MD5(NTOWFv2, serverChallenge | temp) + hmac_md5(ntowf, 16, serverChallenge, 8, temp, tempLen, nt); + // SessionBaseKey = HMAC-MD5(NTOWFv2, NTProofStr) + hmac_md5(ntowf, 16, nt, 16, nullptr, 0, sessionKey); + + // LMv2 response; all zero when the server supplied a timestamp. + memset(lm, 0, 24); + if (!haveTimestamp) { + hmac_md5(ntowf, 16, serverChallenge, 8, p.clientChallenge, 8, lm); + memcpy(lm + 16, p.clientChallenge, 8); + } + memset(ntowf, 0, sizeof(ntowf)); + + uint32_t off = (uint32_t)kHeader; + put_field(out + 12, 24, off); off += 24; + put_field(out + 20, (uint16_t)ntRespLen, off); off += (uint32_t)ntRespLen; + put_field(out + 28, (uint16_t)domainLen, off); + memcpy(out + off, domain16, (size_t)domainLen); off += (uint32_t)domainLen; + put_field(out + 36, (uint16_t)userLen, off); + memcpy(out + off, user16, (size_t)userLen); off += (uint32_t)userLen; + put_field(out + 44, 0, off); // workstation + put_field(out + 52, 0, off); // encrypted session key + put32(out + 60, kClientFlags); + return (int)off; + } + + // ========================================================================== + // SPNEGO (RFC 4178), just enough DER to carry one NTLM token + // ========================================================================== + + static size_t der_len_size(size_t len) { return len < 0x80 ? 1 : (len < 0x100 ? 2 : 3); } + + static size_t der_put_len(uint8_t* p, size_t len) { + if (len < 0x80) { p[0] = (uint8_t)len; return 1; } + if (len < 0x100) { p[0] = 0x81; p[1] = (uint8_t)len; return 2; } + p[0] = 0x82; p[1] = (uint8_t)(len >> 8); p[2] = (uint8_t)len; + return 3; + } + + static size_t der_tlv_size(size_t contentLen) { return 1 + der_len_size(contentLen) + contentLen; } + + static const uint8_t kSpnegoOid[] = {0x06, 0x06, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x02}; + // mechTypes [0] { SEQUENCE { OID 1.3.6.1.4.1.311.2.2.10 (NTLMSSP) } } + static const uint8_t kMechTypes[] = {0xA0, 0x0E, 0x30, 0x0C, 0x06, 0x0A, 0x2B, 0x06, 0x01, + 0x04, 0x01, 0x82, 0x37, 0x02, 0x02, 0x0A}; + + int spnego_wrap(const uint8_t* token, size_t tokenLen, bool first, uint8_t* out, size_t outCap) { + if (tokenLen > 0xFF00) return -1; + size_t octet = der_tlv_size(tokenLen); // OCTET STRING { token } + size_t tagged = der_tlv_size(octet); // [2] { ... } + size_t seqContent = tagged + (first ? sizeof(kMechTypes) : 0); + size_t seq = der_tlv_size(seqContent); // SEQUENCE { ... } + size_t choice = der_tlv_size(seq); // [0] NegTokenInit / [1] NegTokenResp + size_t total = first ? der_tlv_size(sizeof(kSpnegoOid) + choice) : choice; + if (total > outCap) return -1; + + uint8_t* p = out; + if (first) { + *p++ = 0x60; // APPLICATION 0 + p += der_put_len(p, sizeof(kSpnegoOid) + choice); + memcpy(p, kSpnegoOid, sizeof(kSpnegoOid)); + p += sizeof(kSpnegoOid); + } + *p++ = first ? 0xA0 : 0xA1; + p += der_put_len(p, seq); + *p++ = 0x30; + p += der_put_len(p, seqContent); + if (first) { + memcpy(p, kMechTypes, sizeof(kMechTypes)); + p += sizeof(kMechTypes); + } + *p++ = 0xA2; // mechToken / responseToken + p += der_put_len(p, octet); + *p++ = 0x04; + p += der_put_len(p, tokenLen); + memcpy(p, token, tokenLen); + p += tokenLen; + return (int)(p - out); + } + + // Read one DER header at *pos. Returns false if it runs past `len`. + static bool der_read(const uint8_t* d, size_t len, size_t* pos, uint8_t* tag, size_t* contentLen) { + size_t p = *pos; + if (p + 2 > len) return false; + *tag = d[p++]; + size_t l = d[p++]; + if (l & 0x80) { + size_t n = l & 0x7F; + if (n == 0 || n > 3 || p + n > len) return false; + l = 0; + for (size_t i = 0; i < n; i++) l = (l << 8) | d[p++]; + } + if (l > len - p) return false; + *contentLen = l; + *pos = p; + return true; + } + + bool spnego_unwrap(const uint8_t* blob, size_t len, const uint8_t** token, size_t* tokenLen) { + if (len >= 8 && memcmp(blob, kSignature, 8) == 0) { // raw NTLMSSP + *token = blob; + *tokenLen = len; + return true; + } + + // NegTokenResp: [1] { SEQUENCE { [0] negState, [1] mech, [2] { OCTET STRING } ... } } + size_t pos = 0; + uint8_t tag; + size_t clen; + if (der_read(blob, len, &pos, &tag, &clen) && tag == 0xA1) { + size_t end = pos + clen; + if (der_read(blob, end, &pos, &tag, &clen) && tag == 0x30) { + end = pos + clen; + while (pos < end && der_read(blob, end, &pos, &tag, &clen)) { + if (tag == 0xA2) { + size_t inner = pos; + uint8_t t2; + size_t l2; + if (der_read(blob, pos + clen, &inner, &t2, &l2) && t2 == 0x04 && + l2 >= 8 && memcmp(blob + inner, kSignature, 8) == 0) { + *token = blob + inner; + *tokenLen = l2; + return true; + } + } + pos += clen; + } + } + } + + // Unusual framing: fall back to locating the NTLMSSP signature. + for (size_t i = 0; i + 8 <= len; i++) { + if (memcmp(blob + i, kSignature, 8) == 0) { + *token = blob + i; + *tokenLen = len - i; + return true; + } + } + return false; + } + +} diff --git a/programs/lib/smb/smb.cpp b/programs/lib/smb/smb.cpp new file mode 100644 index 0000000..1e9710f --- /dev/null +++ b/programs/lib/smb/smb.cpp @@ -0,0 +1,1252 @@ +/* + * smb.cpp + * SMB2/SMB3 client: transport, session, files, directories, share listing + * Copyright (c) 2026 Daniel Hammer +*/ + +#include "internal.hpp" +#include + +namespace smb { + + using namespace detail; + + // ========================================================================== + // Wire constants + // ========================================================================== + + static constexpr uint32_t HDR = 64; // SMB2 header size + static constexpr uint32_t NBSS = 4; // TCP framing: 0x00 + 24-bit length + // Refuse server messages larger than this (we never ask for more than + // MAX_IO of payload). + static constexpr uint32_t MAX_MESSAGE = 1024 * 1024; + + enum Command : uint16_t { + CMD_NEGOTIATE = 0, CMD_SESSION_SETUP = 1, CMD_LOGOFF = 2, CMD_TREE_CONNECT = 3, + CMD_TREE_DISCONNECT = 4, CMD_CREATE = 5, CMD_CLOSE = 6, CMD_READ = 8, CMD_WRITE = 9, + CMD_IOCTL = 11, CMD_ECHO = 13, CMD_QUERY_DIRECTORY = 14, CMD_QUERY_INFO = 16, + CMD_SET_INFO = 17 + }; + + static constexpr uint32_t FLAG_RESPONSE = 0x1; + static constexpr uint32_t FLAG_ASYNC = 0x2; + static constexpr uint32_t FLAG_SIGNED = 0x8; + + // NTSTATUS values this client distinguishes. + static constexpr uint32_t NT_SUCCESS = 0x00000000; + static constexpr uint32_t NT_PENDING = 0x00000103; + static constexpr uint32_t NT_BUFFER_OVERFLOW = 0x80000005; + static constexpr uint32_t NT_NO_MORE_FILES = 0x80000006; + static constexpr uint32_t NT_INVALID_PARAMETER = 0xC000000D; + static constexpr uint32_t NT_NO_SUCH_FILE = 0xC000000F; + static constexpr uint32_t NT_END_OF_FILE = 0xC0000011; + static constexpr uint32_t NT_MORE_PROCESSING_REQUIRED = 0xC0000016; + static constexpr uint32_t NT_ACCESS_DENIED = 0xC0000022; + static constexpr uint32_t NT_OBJECT_NAME_INVALID = 0xC0000033; + static constexpr uint32_t NT_OBJECT_NAME_NOT_FOUND = 0xC0000034; + static constexpr uint32_t NT_OBJECT_NAME_COLLISION = 0xC0000035; + static constexpr uint32_t NT_OBJECT_PATH_NOT_FOUND = 0xC000003A; + static constexpr uint32_t NT_SHARING_VIOLATION = 0xC0000043; + static constexpr uint32_t NT_NO_SUCH_USER = 0xC0000064; + static constexpr uint32_t NT_WRONG_PASSWORD = 0xC000006A; + static constexpr uint32_t NT_LOGON_FAILURE = 0xC000006D; + static constexpr uint32_t NT_ACCOUNT_RESTRICTION = 0xC000006E; + static constexpr uint32_t NT_PASSWORD_EXPIRED = 0xC0000071; + static constexpr uint32_t NT_ACCOUNT_DISABLED = 0xC0000072; + static constexpr uint32_t NT_DISK_FULL = 0xC000007F; + static constexpr uint32_t NT_MEDIA_WRITE_PROTECTED = 0xC00000A2; + static constexpr uint32_t NT_FILE_IS_A_DIRECTORY = 0xC00000BA; + static constexpr uint32_t NT_NOT_SUPPORTED = 0xC00000BB; + static constexpr uint32_t NT_BAD_NETWORK_NAME = 0xC00000CC; + static constexpr uint32_t NT_DIRECTORY_NOT_EMPTY = 0xC0000101; + static constexpr uint32_t NT_NOT_A_DIRECTORY = 0xC0000103; + static constexpr uint32_t NT_CANNOT_DELETE = 0xC0000121; + static constexpr uint32_t NT_ACCOUNT_LOCKED_OUT = 0xC0000234; + + // Access masks. + static constexpr uint32_t FILE_READ_DATA = 0x00000001; // also FILE_LIST_DIRECTORY + static constexpr uint32_t FILE_READ_ATTRIBUTES = 0x00000080; + static constexpr uint32_t FILE_WRITE_ATTRIBUTES = 0x00000100; + static constexpr uint32_t ACCESS_DELETE = 0x00010000; + static constexpr uint32_t ACCESS_SYNCHRONIZE = 0x00100000; + static constexpr uint32_t FILE_GENERIC_READ = 0x00120089; + static constexpr uint32_t FILE_GENERIC_RW = 0x0012019F; + + static constexpr uint32_t SHARE_ALL = 0x7; // read | write | delete + + static constexpr uint32_t DISP_OPEN = 1; + static constexpr uint32_t DISP_CREATE = 2; + static constexpr uint32_t DISP_OVERWRITE_IF = 5; + + static constexpr uint32_t OPT_DIRECTORY = 0x00000001; + static constexpr uint32_t OPT_NON_DIRECTORY = 0x00000040; + + static constexpr uint32_t ATTR_NORMAL = 0x80; + + // ========================================================================== + // Text + // ========================================================================== + + namespace detail { + + int utf8_to_utf16(const char* in, uint8_t* out, uint32_t cap, bool path) { + const uint8_t* s = (const uint8_t*)in; + uint32_t n = 0; + bool lastSep = true; // swallows leading separators + while (*s) { + uint32_t cp; + uint8_t b = *s++; + if (b < 0x80) { + cp = b; + } else if ((b & 0xE0) == 0xC0 && (s[0] & 0xC0) == 0x80) { + cp = ((uint32_t)(b & 0x1F) << 6) | (s[0] & 0x3F); + s += 1; + } else if ((b & 0xF0) == 0xE0 && (s[0] & 0xC0) == 0x80 && (s[1] & 0xC0) == 0x80) { + cp = ((uint32_t)(b & 0x0F) << 12) | ((uint32_t)(s[0] & 0x3F) << 6) | (s[1] & 0x3F); + s += 2; + } else if ((b & 0xF8) == 0xF0 && (s[0] & 0xC0) == 0x80 && (s[1] & 0xC0) == 0x80 && + (s[2] & 0xC0) == 0x80) { + cp = ((uint32_t)(b & 0x07) << 18) | ((uint32_t)(s[0] & 0x3F) << 12) | + ((uint32_t)(s[1] & 0x3F) << 6) | (s[2] & 0x3F); + s += 3; + } else { + cp = 0xFFFD; // invalid byte + } + + if (path) { + if (cp == '/' || cp == '\\') { + if (lastSep) continue; + cp = '\\'; + lastSep = true; + } else { + lastSep = false; + } + } + + if (cp >= 0x10000) { + if (n + 4 > cap) return -1; + cp -= 0x10000; + put16(out + n, (uint16_t)(0xD800 | (cp >> 10))); + put16(out + n + 2, (uint16_t)(0xDC00 | (cp & 0x3FF))); + n += 4; + } else { + if (n + 2 > cap) return -1; + put16(out + n, (uint16_t)cp); + n += 2; + } + } + // Drop a trailing separator ("dir/" names the directory). + if (path && n >= 2 && get16(out + n - 2) == '\\') n -= 2; + return (int)n; + } + + void utf16_to_utf8(const uint8_t* in, uint32_t len, char* out, uint32_t cap) { + uint32_t n = 0; + if (cap == 0) return; + for (uint32_t i = 0; i + 1 < len; i += 2) { + uint32_t cp = get16(in + i); + if (cp == 0) break; + if (cp >= 0xD800 && cp <= 0xDBFF && i + 3 < len) { + uint32_t lo = get16(in + i + 2); + if (lo >= 0xDC00 && lo <= 0xDFFF) { + cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00); + i += 2; + } + } + uint32_t need = cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4; + if (n + need >= cap) break; + if (need == 1) { + out[n++] = (char)cp; + } else if (need == 2) { + out[n++] = (char)(0xC0 | (cp >> 6)); + out[n++] = (char)(0x80 | (cp & 0x3F)); + } else if (need == 3) { + out[n++] = (char)(0xE0 | (cp >> 12)); + out[n++] = (char)(0x80 | ((cp >> 6) & 0x3F)); + out[n++] = (char)(0x80 | (cp & 0x3F)); + } else { + out[n++] = (char)(0xF0 | (cp >> 18)); + out[n++] = (char)(0x80 | ((cp >> 12) & 0x3F)); + out[n++] = (char)(0x80 | ((cp >> 6) & 0x3F)); + out[n++] = (char)(0x80 | (cp & 0x3F)); + } + } + out[n] = '\0'; + } + + } + + static void copy_str(char* dst, const char* src, size_t cap) { + size_t i = 0; + if (src != nullptr) { + for (; i + 1 < cap && src[i]; i++) dst[i] = src[i]; + } + dst[i] = '\0'; + } + + // ========================================================================== + // Status mapping + // ========================================================================== + + static int map_status(uint32_t nt) { + switch (nt) { + case NT_SUCCESS: return OK; + case NT_ACCESS_DENIED: return ERR_ACCESS; + case NT_NO_SUCH_FILE: + case NT_OBJECT_NAME_NOT_FOUND: + case NT_OBJECT_PATH_NOT_FOUND: return ERR_NOT_FOUND; + case NT_OBJECT_NAME_COLLISION: return ERR_EXISTS; + case NT_OBJECT_NAME_INVALID: + case NT_INVALID_PARAMETER: return ERR_INVALID; + case NT_SHARING_VIOLATION: return ERR_BUSY; + case NT_NO_SUCH_USER: + case NT_WRONG_PASSWORD: + case NT_LOGON_FAILURE: + case NT_ACCOUNT_RESTRICTION: + case NT_PASSWORD_EXPIRED: + case NT_ACCOUNT_DISABLED: + case NT_ACCOUNT_LOCKED_OUT: return ERR_AUTH; + case NT_DISK_FULL: return ERR_NO_SPACE; + case NT_MEDIA_WRITE_PROTECTED: return ERR_READ_ONLY; + case NT_FILE_IS_A_DIRECTORY: return ERR_IS_DIR; + case NT_NOT_A_DIRECTORY: return ERR_NOT_DIR; + case NT_NOT_SUPPORTED: return ERR_UNSUPPORTED; + case NT_BAD_NETWORK_NAME: return ERR_BAD_SHARE; + case NT_DIRECTORY_NOT_EMPTY: return ERR_NOT_EMPTY; + case NT_CANNOT_DELETE: return ERR_ACCESS; + default: return ERR_FAILED; + } + } + + const char* status_text(int status) { + switch (status) { + case OK: return "OK"; + case ERR_IO: return "connection lost"; + case ERR_TIMEOUT: return "server did not respond"; + case ERR_PROTOCOL: return "unexpected reply from server"; + case ERR_AUTH: return "wrong user name or password"; + case ERR_ACCESS: return "access denied"; + case ERR_NOT_FOUND: return "not found"; + case ERR_EXISTS: return "already exists"; + case ERR_NOT_EMPTY: return "directory not empty"; + case ERR_IS_DIR: return "is a directory"; + case ERR_NOT_DIR: return "not a directory"; + case ERR_BUSY: return "file is in use"; + case ERR_NO_SPACE: return "no space left on the share"; + case ERR_UNSUPPORTED: return "server requires a feature this client lacks"; + case ERR_BAD_SHARE: return "no such share"; + case ERR_NOMEM: return "out of memory"; + case ERR_INVALID: return "invalid name or argument"; + case ERR_SIGNATURE: return "server message failed signature check"; + case ERR_READ_ONLY: return "share is read-only"; + default: return "server reported an error"; + } + } + + // ========================================================================== + // Transport + // ========================================================================== + + static bool ensure_buf(Client* c, uint32_t need) { + if (need <= c->bufCap) return true; + uint32_t cap = c->bufCap ? c->bufCap : 4096; + while (cap < need) cap *= 2; + uint8_t* fresh = (uint8_t*)malloc(cap); + if (fresh == nullptr) return false; + if (c->buf != nullptr) { + memcpy(fresh, c->buf, c->bufCap); + free(c->buf); + } + c->buf = fresh; + c->bufCap = cap; + return true; + } + + static int recv_exact(Client* c, uint8_t* p, uint32_t len) { + uint32_t got = 0; + while (got < len) { + int r = c->io.recv(c->io.ctx, p + got, len - got, c->timeoutMs); + if (r < 0) return ERR_IO; + if (r == 0) return ERR_TIMEOUT; + got += (uint32_t)r; + } + return OK; + } + + // The message (header + body) being built or just received. + static inline uint8_t* msg(Client* c) { return c->buf + NBSS; } + static inline uint8_t* body(Client* c) { return c->buf + NBSS + HDR; } + + // Start a request: zeroed header plus `bodyLen` zeroed body bytes. Returns + // the body, or nullptr if out of memory. + static uint8_t* begin(Client* c, uint32_t bodyLen) { + if (!ensure_buf(c, NBSS + HDR + bodyLen)) return nullptr; + memset(c->buf, 0, NBSS + HDR + bodyLen); + return body(c); + } + + static void sign(Client* c, uint8_t* m, uint32_t len, uint8_t out[16]) { + if (c->dialect >= 0x0300) { + aes_cmac(c->signingKey, m, len, out); + } else { + uint8_t full[32]; + hmac_sha256(c->signingKey, 16, m, len, nullptr, 0, full); + memcpy(out, full, 16); + } + } + + // Send the request of `bodyLen` body bytes built with begin() and receive + // its response into the same buffer. Returns OK when a response arrived + // (its NTSTATUS is in *nt), otherwise a transport-level Status. + static int transact(Client* c, uint16_t cmd, uint32_t tree, uint32_t bodyLen, uint32_t* nt) { + uint32_t len = HDR + bodyLen; + uint8_t* m = msg(c); + uint64_t mid = c->messageId++; + + m[0] = 0xFE; m[1] = 'S'; m[2] = 'M'; m[3] = 'B'; + put16(m + 4, 64); + put16(m + 6, c->dialect >= 0x0210 ? 1 : 0); // credit charge + put16(m + 12, cmd); + put16(m + 14, 64); // credits requested + put64(m + 24, mid); + put32(m + 36, tree); + put64(m + 40, c->sessionId); + if (c->signing) { + put32(m + 16, FLAG_SIGNED); + uint8_t sig[16]; + sign(c, m, len, sig); + memcpy(m + 48, sig, 16); + } + + c->buf[0] = 0; + c->buf[1] = (uint8_t)(len >> 16); + c->buf[2] = (uint8_t)(len >> 8); + c->buf[3] = (uint8_t)len; + if (c->io.send(c->io.ctx, c->buf, NBSS + len) != 0) { + c->connected = false; + return ERR_IO; + } + + for (;;) { + uint8_t nb[4]; + int r = recv_exact(c, nb, 4); + if (r != OK) { c->connected = false; return r; } + uint32_t rlen = ((uint32_t)nb[1] << 16) | ((uint32_t)nb[2] << 8) | nb[3]; + if (nb[0] != 0 || rlen < HDR || rlen > MAX_MESSAGE || !ensure_buf(c, NBSS + rlen)) { + c->connected = false; + return nb[0] != 0 || rlen < HDR || rlen > MAX_MESSAGE ? ERR_PROTOCOL : ERR_NOMEM; + } + r = recv_exact(c, c->buf + NBSS, rlen); + if (r != OK) { c->connected = false; return r; } + + m = msg(c); + if (m[0] != 0xFE || m[1] != 'S' || m[2] != 'M' || m[3] != 'B' || get16(m + 4) != 64) { + c->connected = false; + return ERR_PROTOCOL; + } + uint32_t flags = get32(m + 16); + uint32_t status = get32(m + 8); + // Skip anything that is not the answer to this request: stray + // notifications, and "still working" interim responses. + if ((flags & FLAG_RESPONSE) == 0 || get64(m + 24) != mid) continue; + if ((flags & FLAG_ASYNC) != 0 && status == NT_PENDING) continue; + + if (c->signing && (flags & FLAG_SIGNED) != 0) { + uint8_t theirs[16], ours[16]; + memcpy(theirs, m + 48, 16); + memset(m + 48, 0, 16); + sign(c, m, rlen, ours); + if (memcmp(theirs, ours, 16) != 0) { + c->connected = false; + return ERR_SIGNATURE; + } + } + + c->respLen = rlen; + *nt = status; + if (status != NT_SUCCESS) c->lastNtStatus = status; + return OK; + } + } + + // True if the response body holds at least `n` bytes. + static inline bool have(Client* c, uint32_t n) { return c->respLen >= HDR + n; } + + // Validate an (offset, length) pair that is relative to the SMB2 header + // and return a pointer to the data, or nullptr. + static const uint8_t* span(Client* c, uint32_t offset, uint32_t length) { + if (length == 0) return msg(c); + if (offset < HDR || offset > c->respLen || length > c->respLen - offset) return nullptr; + return msg(c) + offset; + } + + // Run a request whose only interesting outcome is its status. + static int simple(Client* c, uint16_t cmd, uint32_t tree, uint32_t bodyLen) { + uint32_t nt; + int r = transact(c, cmd, tree, bodyLen, &nt); + if (r != OK) return r; + return map_status(nt); + } + + // ========================================================================== + // Negotiate + session setup + // ========================================================================== + + static int negotiate(Client* c, uint64_t* serverTime) { + static const uint16_t dialects[] = {0x0202, 0x0210, 0x0300, 0x0302}; + const uint32_t count = sizeof(dialects) / sizeof(dialects[0]); + uint32_t bodyLen = 36 + count * 2; + uint8_t* b = begin(c, bodyLen); + if (b == nullptr) return ERR_NOMEM; + put16(b, 36); + put16(b + 2, (uint16_t)count); + put16(b + 4, 1); // signing enabled + c->io.random(c->io.ctx, b + 12, 16); // client GUID + for (uint32_t i = 0; i < count; i++) put16(b + 36 + i * 2, dialects[i]); + + uint32_t nt; + int r = transact(c, CMD_NEGOTIATE, 0, bodyLen, &nt); + if (r != OK) return r; + if (nt != NT_SUCCESS) return nt == NT_NOT_SUPPORTED ? ERR_UNSUPPORTED : map_status(nt); + if (!have(c, 64)) return ERR_PROTOCOL; + + b = body(c); + uint16_t securityMode = get16(b + 2); + uint16_t dialect = get16(b + 4); + bool known = false; + for (uint32_t i = 0; i < count; i++) known = known || dialects[i] == dialect; + if (!known) return ERR_UNSUPPORTED; + + c->dialect = dialect; + c->serverRequiresSigning = (securityMode & 2) != 0; + c->maxTransact = get32(b + 28); + c->maxRead = get32(b + 32); + c->maxWrite = get32(b + 36); + if (c->maxRead > MAX_IO || c->maxRead == 0) c->maxRead = MAX_IO; + if (c->maxWrite > MAX_IO || c->maxWrite == 0) c->maxWrite = MAX_IO; + if (c->maxTransact > MAX_IO || c->maxTransact == 0) c->maxTransact = MAX_IO; + *serverTime = get64(b + 40); + return OK; + } + + // One SESSION_SETUP round trip carrying `blob`. On return the response's + // security blob is at *outBlob (inside the client buffer). + static int session_setup(Client* c, const uint8_t* blob, uint32_t blobLen, uint32_t* nt, + const uint8_t** outBlob, uint32_t* outLen, uint16_t* sessionFlags) { + uint32_t bodyLen = 24 + blobLen; + uint8_t* b = begin(c, bodyLen); + if (b == nullptr) return ERR_NOMEM; + put16(b, 25); + b[3] = 1; // signing enabled + put16(b + 12, (uint16_t)(HDR + 24)); // security buffer offset + put16(b + 14, (uint16_t)blobLen); + memcpy(b + 24, blob, blobLen); + + int r = transact(c, CMD_SESSION_SETUP, 0, bodyLen, nt); + if (r != OK) return r; + if (*nt != NT_SUCCESS && *nt != NT_MORE_PROCESSING_REQUIRED) return OK; + if (!have(c, 8)) return ERR_PROTOCOL; + + b = body(c); + *sessionFlags = get16(b + 2); + uint16_t off = get16(b + 4); + uint16_t len = get16(b + 6); + const uint8_t* p = span(c, off, len); + if (p == nullptr) return ERR_PROTOCOL; + *outBlob = p; + *outLen = len; + c->sessionId = get64(msg(c) + 40); + return OK; + } + + // Run one complete NTLM logon. Returns OK, ERR_AUTH (try another identity), + // or a fatal Status. + static int logon(Client* c, const char* user, const char* password, const char* domain, + bool anonymous, uint64_t serverTime) { + uint8_t token[2048]; + uint8_t blob[2200]; + uint8_t challenge[1024]; + + c->sessionId = 0; + c->signing = false; + + uint8_t negotiateMsg[NTLM_NEGOTIATE_LEN]; + ntlm_negotiate(negotiateMsg); + int blobLen = spnego_wrap(negotiateMsg, sizeof(negotiateMsg), true, blob, sizeof(blob)); + if (blobLen < 0) return ERR_NOMEM; + + uint32_t nt; + const uint8_t* reply = nullptr; + uint32_t replyLen = 0; + uint16_t sessionFlags = 0; + int r = session_setup(c, blob, (uint32_t)blobLen, &nt, &reply, &replyLen, &sessionFlags); + if (r != OK) return r; + if (nt != NT_MORE_PROCESSING_REQUIRED) return nt == NT_SUCCESS ? ERR_PROTOCOL : map_status(nt); + + const uint8_t* ch = nullptr; + size_t chLen = 0; + if (!spnego_unwrap(reply, replyLen, &ch, &chLen) || chLen > sizeof(challenge)) return ERR_PROTOCOL; + memcpy(challenge, ch, chLen); + + NtlmAuthParams params; + params.user = user; + params.password = password; + params.domain = domain; + params.anonymous = anonymous; + params.fallbackTime = serverTime; + c->io.random(c->io.ctx, params.clientChallenge, 8); + + uint8_t sessionKey[16]; + int tokenLen = ntlm_authenticate(challenge, chLen, params, token, sizeof(token), sessionKey); + if (tokenLen < 0) return tokenLen; + blobLen = spnego_wrap(token, (size_t)tokenLen, false, blob, sizeof(blob)); + memset(token, 0, sizeof(token)); + if (blobLen < 0) return ERR_NOMEM; + + r = session_setup(c, blob, (uint32_t)blobLen, &nt, &reply, &replyLen, &sessionFlags); + if (r != OK) return r; + if (nt != NT_SUCCESS) { + c->sessionId = 0; + return map_status(nt) == ERR_FAILED ? ERR_AUTH : map_status(nt); + } + + // SessionFlags: 1 = guest, 2 = null session, 4 = encrypt everything. + if (sessionFlags & 0x4) return ERR_UNSUPPORTED; + c->guest = anonymous || (sessionFlags & 0x3) != 0; + + if (!c->guest) { + if (c->dialect >= 0x0300) { + smb3_kdf(sessionKey, "SMB2AESCMAC", 12, "SmbSign", 8, c->signingKey); + } else { + memcpy(c->signingKey, sessionKey, 16); + } + c->signing = true; + } else if (c->serverRequiresSigning) { + // A guest session has no usable key, so it cannot sign. + return ERR_AUTH; + } + memset(sessionKey, 0, sizeof(sessionKey)); + return OK; + } + + int connect(Client* c, const Io& io, const char* serverName, const Credentials& creds) { + memset(c, 0, sizeof(*c)); + c->io = io; + c->timeoutMs = 20000; + c->dialect = 0x0202; + copy_str(c->server, serverName, sizeof(c->server)); + if (!ensure_buf(c, NBSS + HDR + 512 + MAX_IO)) return ERR_NOMEM; + c->connected = true; + + uint64_t serverTime = 0; + int r = negotiate(c, &serverTime); + if (r == OK) { + const char* user = creds.user ? creds.user : ""; + const char* password = creds.password ? creds.password : ""; + const char* domain = creds.domain ? creds.domain : ""; + if (user[0] != '\0') { + r = logon(c, user, password, domain, false, serverTime); + } else { + // No identity given: the guest account, then a null session. + r = logon(c, "guest", "", "", false, serverTime); + if (r == ERR_AUTH && c->connected) r = logon(c, "", "", "", true, serverTime); + } + } + if (r != OK) c->connected = false; + return r; + } + + void disconnect(Client* c) { + if (c->connected && c->sessionId != 0) { + uint8_t* b = begin(c, 4); + if (b != nullptr) { + put16(b, 4); + simple(c, CMD_LOGOFF, 0, 4); + } + } + if (c->buf != nullptr) free(c->buf); + memset(c->signingKey, 0, sizeof(c->signingKey)); + c->buf = nullptr; + c->bufCap = 0; + c->connected = false; + c->sessionId = 0; + c->signing = false; + } + + int echo(Client* c) { + if (!c->connected) return ERR_IO; + uint8_t* b = begin(c, 4); + if (b == nullptr) return ERR_NOMEM; + put16(b, 4); + return simple(c, CMD_ECHO, 0, 4); + } + + // ========================================================================== + // Shares + // ========================================================================== + + int tree_connect(Client* c, const char* share, uint32_t* outTreeId) { + if (!c->connected) return ERR_IO; + char unc[600]; + size_t n = 0; + unc[n++] = '\\'; unc[n++] = '\\'; + for (const char* s = c->server; *s && n + 2 < sizeof(unc); s++) unc[n++] = *s; + unc[n++] = '\\'; + for (const char* s = share; *s && n + 1 < sizeof(unc); s++) unc[n++] = *s; + unc[n] = '\0'; + + uint8_t path16[1200]; + int pathLen = utf8_to_utf16(unc, path16, sizeof(path16)); + if (pathLen <= 0) return ERR_INVALID; + + uint32_t bodyLen = 8 + (uint32_t)pathLen; + uint8_t* b = begin(c, bodyLen); + if (b == nullptr) return ERR_NOMEM; + put16(b, 9); + put16(b + 4, (uint16_t)(HDR + 8)); + put16(b + 6, (uint16_t)pathLen); + memcpy(b + 8, path16, (size_t)pathLen); + + uint32_t nt; + int r = transact(c, CMD_TREE_CONNECT, 0, bodyLen, &nt); + if (r != OK) return r; + if (nt != NT_SUCCESS) { + // Servers disagree on the status for an unknown share name. + int st = map_status(nt); + return st == ERR_NOT_FOUND ? ERR_BAD_SHARE : st; + } + if (!have(c, 16)) return ERR_PROTOCOL; + + uint32_t tree = get32(msg(c) + 36); + uint32_t shareFlags = get32(body(c) + 4); + if (shareFlags & 0x8000) { // SMB2_SHAREFLAG_ENCRYPT_DATA + tree_disconnect(c, tree); + return ERR_UNSUPPORTED; + } + *outTreeId = tree; + return OK; + } + + int tree_disconnect(Client* c, uint32_t treeId) { + if (!c->connected) return ERR_IO; + uint8_t* b = begin(c, 4); + if (b == nullptr) return ERR_NOMEM; + put16(b, 4); + return simple(c, CMD_TREE_DISCONNECT, treeId, 4); + } + + // ========================================================================== + // Create / close + // ========================================================================== + + static void fill_info(FileInfo* info, uint64_t ctime, uint64_t atime, uint64_t wtime, + uint64_t size, uint32_t attrs) { + info->ctime = filetime_to_unix(ctime); + info->atime = filetime_to_unix(atime); + info->mtime = filetime_to_unix(wtime); + info->attributes = attrs; + info->isDir = (attrs & ATTR_DIRECTORY) != 0; + info->size = info->isDir ? 0 : size; + } + + static int create(Client* c, uint32_t tree, const char* path, uint32_t access, uint32_t attrs, + uint32_t disposition, uint32_t options, FileId* outId, FileInfo* outInfo) { + if (!c->connected) return ERR_IO; + uint8_t name16[1536]; + int nameLen = utf8_to_utf16(path ? path : "", name16, sizeof(name16), true); + if (nameLen < 0) return ERR_INVALID; + + // The buffer must hold at least one byte even for the share root. + uint32_t bodyLen = 56 + (nameLen > 0 ? (uint32_t)nameLen : 1); + uint8_t* b = begin(c, bodyLen); + if (b == nullptr) return ERR_NOMEM; + put16(b, 57); + put32(b + 4, 2); // impersonation level: Impersonation + put32(b + 24, access); + put32(b + 28, attrs); + put32(b + 32, SHARE_ALL); + put32(b + 36, disposition); + put32(b + 40, options); + put16(b + 44, (uint16_t)(HDR + 56)); + put16(b + 46, (uint16_t)nameLen); + if (nameLen > 0) memcpy(b + 56, name16, (size_t)nameLen); + + uint32_t nt; + int r = transact(c, CMD_CREATE, tree, bodyLen, &nt); + if (r != OK) return r; + if (nt != NT_SUCCESS) return map_status(nt); + if (!have(c, 88)) return ERR_PROTOCOL; + + b = body(c); + if (outInfo != nullptr) { + fill_info(outInfo, get64(b + 8), get64(b + 16), get64(b + 24), get64(b + 48), get32(b + 56)); + } + memcpy(outId->raw, b + 64, 16); + return OK; + } + + int close(Client* c, uint32_t tree, const FileId& id) { + if (!c->connected) return ERR_IO; + uint8_t* b = begin(c, 24); + if (b == nullptr) return ERR_NOMEM; + put16(b, 24); + memcpy(b + 8, id.raw, 16); + return simple(c, CMD_CLOSE, tree, 24); + } + + int open(Client* c, uint32_t tree, const char* path, OpenMode mode, FileId* outId, FileInfo* outInfo) { + switch (mode) { + case OPEN_READ: + return create(c, tree, path, FILE_GENERIC_READ, 0, DISP_OPEN, OPT_NON_DIRECTORY, outId, outInfo); + case OPEN_READWRITE: + return create(c, tree, path, FILE_GENERIC_RW, 0, DISP_OPEN, OPT_NON_DIRECTORY, outId, outInfo); + case OPEN_CREATE: + return create(c, tree, path, FILE_GENERIC_RW, ATTR_NORMAL, DISP_OVERWRITE_IF, + OPT_NON_DIRECTORY, outId, outInfo); + case OPEN_CREATE_NEW: + return create(c, tree, path, FILE_GENERIC_RW, ATTR_NORMAL, DISP_CREATE, + OPT_NON_DIRECTORY, outId, outInfo); + } + return ERR_INVALID; + } + + // ========================================================================== + // Read / write + // ========================================================================== + + int read(Client* c, uint32_t tree, const FileId& id, uint64_t offset, void* buf, uint32_t len) { + if (!c->connected) return ERR_IO; + if (len == 0) return 0; + if (len > c->maxRead) len = c->maxRead; + + uint8_t* b = begin(c, 49); + if (b == nullptr) return ERR_NOMEM; + put16(b, 49); + put32(b + 4, len); + put64(b + 8, offset); + memcpy(b + 16, id.raw, 16); + + uint32_t nt; + int r = transact(c, CMD_READ, tree, 49, &nt); + if (r != OK) return r; + if (nt == NT_END_OF_FILE) return 0; + if (nt != NT_SUCCESS && nt != NT_BUFFER_OVERFLOW) return map_status(nt); + if (!have(c, 16)) return ERR_PROTOCOL; + + b = body(c); + uint32_t dataOff = b[2]; + uint32_t dataLen = get32(b + 4); + const uint8_t* data = span(c, dataOff, dataLen); + if (data == nullptr) return ERR_PROTOCOL; + if (dataLen > len) dataLen = len; + memcpy(buf, data, dataLen); + return (int)dataLen; + } + + int write(Client* c, uint32_t tree, const FileId& id, uint64_t offset, const void* buf, uint32_t len) { + if (!c->connected) return ERR_IO; + if (len == 0) return 0; + if (len > c->maxWrite) len = c->maxWrite; + + uint32_t bodyLen = 48 + len; + uint8_t* b = begin(c, bodyLen); + if (b == nullptr) return ERR_NOMEM; + put16(b, 49); + put16(b + 2, (uint16_t)(HDR + 48)); + put32(b + 4, len); + put64(b + 8, offset); + memcpy(b + 16, id.raw, 16); + memcpy(b + 48, buf, len); + + uint32_t nt; + int r = transact(c, CMD_WRITE, tree, bodyLen, &nt); + if (r != OK) return r; + if (nt != NT_SUCCESS) return map_status(nt); + if (!have(c, 16)) return ERR_PROTOCOL; + uint32_t count = get32(body(c) + 4); + return (int)(count > len ? len : count); + } + + // ========================================================================== + // Query / set information + // ========================================================================== + + static constexpr uint8_t INFO_FILE = 1; + static constexpr uint8_t FileBasicInformation = 4; + static constexpr uint8_t FileStandardInformation = 5; + static constexpr uint8_t FileRenameInformation = 10; + static constexpr uint8_t FileDispositionInformation = 13; + + int file_size(Client* c, uint32_t tree, const FileId& id, uint64_t* outSize) { + if (!c->connected) return ERR_IO; + uint8_t* b = begin(c, 41); + if (b == nullptr) return ERR_NOMEM; + put16(b, 41); + b[2] = INFO_FILE; + b[3] = FileStandardInformation; + put32(b + 4, 24); // output buffer length + memcpy(b + 24, id.raw, 16); + + uint32_t nt; + int r = transact(c, CMD_QUERY_INFO, tree, 41, &nt); + if (r != OK) return r; + if (nt != NT_SUCCESS) return map_status(nt); + if (!have(c, 8)) return ERR_PROTOCOL; + b = body(c); + const uint8_t* data = span(c, get16(b + 2), get32(b + 4)); + if (data == nullptr || get32(b + 4) < 16) return ERR_PROTOCOL; + *outSize = get64(data + 8); // EndOfFile + return OK; + } + + static int set_info(Client* c, uint32_t tree, const FileId& id, uint8_t infoClass, + const uint8_t* data, uint32_t len) { + uint32_t bodyLen = 32 + len; + uint8_t* b = begin(c, bodyLen); + if (b == nullptr) return ERR_NOMEM; + put16(b, 33); + b[2] = INFO_FILE; + b[3] = infoClass; + put32(b + 4, len); + put16(b + 8, (uint16_t)(HDR + 32)); + memcpy(b + 16, id.raw, 16); + memcpy(b + 32, data, len); + return simple(c, CMD_SET_INFO, tree, bodyLen); + } + + // Open `path` (file or directory) for a metadata operation, run `op`, close. + template + static int with_handle(Client* c, uint32_t tree, const char* path, uint32_t access, Op op) { + FileId id; + int r = create(c, tree, path, access, 0, DISP_OPEN, 0, &id, nullptr); + if (r != OK) return r; + r = op(id); + int cr = close(c, tree, id); + return r != OK ? r : (cr == ERR_IO || cr == ERR_TIMEOUT ? cr : OK); + } + + int stat(Client* c, uint32_t tree, const char* path, FileInfo* out) { + FileId id; + int r = create(c, tree, path, FILE_READ_ATTRIBUTES | ACCESS_SYNCHRONIZE, 0, DISP_OPEN, 0, &id, out); + if (r != OK) return r; + close(c, tree, id); + return c->connected ? OK : ERR_IO; + } + + int mkdir(Client* c, uint32_t tree, const char* path) { + FileId id; + int r = create(c, tree, path, FILE_READ_DATA | FILE_READ_ATTRIBUTES | ACCESS_SYNCHRONIZE, + ATTR_DIRECTORY, DISP_CREATE, OPT_DIRECTORY, &id, nullptr); + if (r != OK) return r; + close(c, tree, id); + return OK; + } + + int remove(Client* c, uint32_t tree, const char* path) { + return with_handle(c, tree, path, ACCESS_DELETE | FILE_READ_ATTRIBUTES | ACCESS_SYNCHRONIZE, + [&](const FileId& id) { + uint8_t deletePending = 1; + return set_info(c, tree, id, FileDispositionInformation, &deletePending, 1); + }); + } + + int rename(Client* c, uint32_t tree, const char* from, const char* to, bool replace) { + // FILE_RENAME_INFORMATION: ReplaceIfExists, 7 reserved, RootDirectory, + // FileNameLength, FileName (full path from the share root). + uint8_t info[20 + 1536]; + memset(info, 0, sizeof(info)); + int nameLen = utf8_to_utf16(to, info + 20, 1536, true); + if (nameLen <= 0) return ERR_INVALID; + info[0] = replace ? 1 : 0; + put32(info + 16, (uint32_t)nameLen); + uint32_t infoLen = 20 + (uint32_t)nameLen; + if (infoLen < 24) infoLen = 24; // some servers reject shorter buffers + + return with_handle(c, tree, from, ACCESS_DELETE | FILE_READ_ATTRIBUTES | ACCESS_SYNCHRONIZE, + [&](const FileId& id) { + return set_info(c, tree, id, FileRenameInformation, info, infoLen); + }); + } + + int set_times(Client* c, uint32_t tree, const char* path, int64_t atime, int64_t mtime) { + // FILE_BASIC_INFORMATION; zero fields are left unchanged by the server. + uint8_t info[40]; + memset(info, 0, sizeof(info)); + put64(info + 8, unix_to_filetime(atime)); + put64(info + 16, unix_to_filetime(mtime)); + return with_handle(c, tree, path, FILE_WRITE_ATTRIBUTES | ACCESS_SYNCHRONIZE, + [&](const FileId& id) { + return set_info(c, tree, id, FileBasicInformation, info, sizeof(info)); + }); + } + + // ========================================================================== + // Directory listing + // ========================================================================== + + int list_dir(Client* c, uint32_t tree, const char* path, DirCallback cb, void* ctx) { + FileId id; + int r = create(c, tree, path, FILE_READ_DATA | FILE_READ_ATTRIBUTES | ACCESS_SYNCHRONIZE, + 0, DISP_OPEN, OPT_DIRECTORY, &id, nullptr); + if (r != OK) return r; + + // Entries are parsed out of the response buffer, and the callback may + // not issue requests, so no copy of the response is needed. + DirEntry* entry = (DirEntry*)malloc(sizeof(DirEntry)); + if (entry == nullptr) { + close(c, tree, id); + return ERR_NOMEM; + } + + int count = 0; + bool stop = false; + while (!stop) { + uint8_t* b = begin(c, 32 + 2); + if (b == nullptr) { r = ERR_NOMEM; break; } + put16(b, 33); + b[2] = 1; // FileDirectoryInformation + memcpy(b + 8, id.raw, 16); + put16(b + 24, (uint16_t)(HDR + 32)); + put16(b + 26, 2); + put32(b + 28, c->maxTransact); + put16(b + 32, '*'); + + uint32_t nt; + r = transact(c, CMD_QUERY_DIRECTORY, tree, 34, &nt); + if (r != OK) break; + if (nt == NT_NO_MORE_FILES || nt == NT_NO_SUCH_FILE) break; + if (nt != NT_SUCCESS) { r = map_status(nt); break; } + if (!have(c, 8)) { r = ERR_PROTOCOL; break; } + + b = body(c); + uint32_t outLen = get32(b + 4); + const uint8_t* data = span(c, get16(b + 2), outLen); + if (data == nullptr) { r = ERR_PROTOCOL; break; } + if (outLen == 0) break; + + uint32_t pos = 0; + for (;;) { + if (outLen - pos < 64) { r = ERR_PROTOCOL; break; } + const uint8_t* e = data + pos; + uint32_t next = get32(e); + uint32_t nameLen = get32(e + 60); + if (nameLen > outLen - pos - 64) { r = ERR_PROTOCOL; break; } + + utf16_to_utf8(e + 64, nameLen, entry->name, sizeof(entry->name)); + bool dots = entry->name[0] == '.' && + (entry->name[1] == '\0' || (entry->name[1] == '.' && entry->name[2] == '\0')); + if (!dots && entry->name[0] != '\0') { + fill_info(&entry->info, get64(e + 8), get64(e + 16), get64(e + 24), + get64(e + 40), get32(e + 56)); + count++; + if (!cb(ctx, *entry)) { stop = true; break; } + } + + if (next == 0) break; + if (next < 64 || next > outLen - pos) { r = ERR_PROTOCOL; break; } + pos += next; + } + if (r != OK) break; + } + + free(entry); + if (c->connected) close(c, tree, id); + return r != OK ? r : count; + } + + // ========================================================================== + // Share enumeration: srvsvc NetrShareEnum over the IPC$ named pipe + // ========================================================================== + + static constexpr uint32_t FSCTL_PIPE_TRANSCEIVE = 0x0011C017; + + // Write `in` to the pipe and read the reply into `out`. Returns the reply + // length or a negative Status. + static int pipe_transceive(Client* c, uint32_t tree, const FileId& pipe, + const uint8_t* in, uint32_t inLen, uint8_t* out, uint32_t outCap) { + uint32_t bodyLen = 56 + inLen; + uint8_t* b = begin(c, bodyLen); + if (b == nullptr) return ERR_NOMEM; + put16(b, 57); + put32(b + 4, FSCTL_PIPE_TRANSCEIVE); + memcpy(b + 8, pipe.raw, 16); + put32(b + 24, HDR + 56); // input offset + put32(b + 28, inLen); + put32(b + 44, c->maxTransact); // max output response + put32(b + 48, 1); // SMB2_0_IOCTL_IS_FSCTL + memcpy(b + 56, in, inLen); + + uint32_t nt; + int r = transact(c, CMD_IOCTL, tree, bodyLen, &nt); + if (r != OK) return r; + if (nt != NT_SUCCESS && nt != NT_BUFFER_OVERFLOW) return map_status(nt); + if (!have(c, 48)) return ERR_PROTOCOL; + + b = body(c); + uint32_t outLen = get32(b + 36); + const uint8_t* data = span(c, get32(b + 32), outLen); + if (data == nullptr || outLen > outCap) return ERR_PROTOCOL; + memcpy(out, data, outLen); + uint32_t total = outLen; + + // The reply did not fit in one transaction, or the RPC answer spans + // several fragments: keep reading the pipe until the last fragment + // (PFC_LAST_FRAG) is complete. + bool more = nt == NT_BUFFER_OVERFLOW; + for (int guard = 0; guard < 64; guard++) { + if (!more) { + // Walk the fragments received so far. + uint32_t pos = 0; + bool last = false; + while (pos + 16 <= total) { + uint32_t fragLen = get16(out + pos + 8); + if (fragLen < 16) return ERR_PROTOCOL; + if (pos + fragLen > total) break; // partial fragment + last = (out[pos + 3] & 0x02) != 0; + pos += fragLen; + } + if (last && pos == total) break; + } + if (total >= outCap) return ERR_PROTOCOL; + int n = read(c, tree, pipe, 0, out + total, outCap - total); + if (n < 0) return n; + if (n == 0) break; + total += (uint32_t)n; + more = false; + } + return (int)total; + } + + // Bounds-checked NDR reader over an RPC response stub. + struct Ndr { + const uint8_t* p; + uint32_t len; + uint32_t pos; + bool ok; + + void align4() { pos = (pos + 3) & ~3u; } + uint32_t u32() { + align4(); + if (!ok || len < 4 || pos > len - 4) { ok = false; return 0; } + uint32_t v = get32(p + pos); + pos += 4; + return v; + } + // Conformant varying UTF-16 string -> UTF-8. + void string(char* out, uint32_t cap) { + uint32_t maxCount = u32(); + uint32_t offset = u32(); + uint32_t actual = u32(); + (void)maxCount; + if (!ok || offset != 0 || actual > (len - pos) / 2) { ok = false; out[0] = '\0'; return; } + utf16_to_utf8(p + pos, actual * 2, out, cap); + pos += actual * 2; + } + }; + + int list_shares(Client* c, ShareInfo* out, int max) { + if (!c->connected) return ERR_IO; + uint32_t tree; + int r = tree_connect(c, "IPC$", &tree); + if (r != OK) return r; + + static constexpr uint32_t kRpcCap = 256 * 1024; + uint8_t* rpc = (uint8_t*)malloc(kRpcCap); + if (rpc == nullptr) { + tree_disconnect(c, tree); + return ERR_NOMEM; + } + + FileId pipe; + r = create(c, tree, "srvsvc", FILE_GENERIC_RW, 0, DISP_OPEN, 0, &pipe, nullptr); + if (r != OK) { + free(rpc); + tree_disconnect(c, tree); + return r; + } + + int result = ERR_PROTOCOL; + do { + // ---- DCE/RPC bind to the srvsvc interface, NDR transfer syntax ---- + static const uint8_t bind[72] = { + 0x05, 0x00, 0x0B, 0x03, 0x10, 0x00, 0x00, 0x00, // v5.0, bind, first|last, LE + 0x48, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // frag 72, auth 0, call id 1 + 0xB8, 0x10, 0xB8, 0x10, 0x00, 0x00, 0x00, 0x00, // max xmit/recv 4280, assoc group + 0x01, 0x00, 0x00, 0x00, // one presentation context + 0x00, 0x00, 0x01, 0x00, // context id 0, one transfer syntax + // srvsvc 4b324fc8-1670-01d3-1278-5a47bf6ee188 v3.0 + 0xC8, 0x4F, 0x32, 0x4B, 0x70, 0x16, 0xD3, 0x01, 0x12, 0x78, 0x5A, 0x47, + 0xBF, 0x6E, 0xE1, 0x88, 0x03, 0x00, 0x00, 0x00, + // NDR 8a885d04-1ceb-11c9-9fe8-08002b104860 v2 + 0x04, 0x5D, 0x88, 0x8A, 0xEB, 0x1C, 0xC9, 0x11, 0x9F, 0xE8, 0x08, 0x00, + 0x2B, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 + }; + int n = pipe_transceive(c, tree, pipe, bind, sizeof(bind), rpc, kRpcCap); + if (n < 0) { result = n; break; } + if (n < 16 || rpc[2] != 0x0C) break; // not a bind_ack + + // ---- NetrShareEnum(server, level 1) ---- + uint8_t req[1400]; + memset(req, 0, sizeof(req)); + uint32_t p = 24; // stub starts after the request header + + char unc[300]; + unc[0] = '\\'; unc[1] = '\\'; + copy_str(unc + 2, c->server, sizeof(unc) - 2); + int nameBytes = utf8_to_utf16(unc, req + p + 16, 600); + if (nameBytes < 0) { result = ERR_INVALID; break; } + uint32_t chars = (uint32_t)nameBytes / 2 + 1; // with terminator + put32(req + p, 0x00020000); // ServerName referent + put32(req + p + 4, chars); + put32(req + p + 8, 0); + put32(req + p + 12, chars); + p += 16 + chars * 2; + p = (p + 3) & ~3u; + put32(req + p, 1); p += 4; // level + put32(req + p, 1); p += 4; // union switch + put32(req + p, 0x00020004); p += 4; // container referent + put32(req + p, 0); p += 4; // entries read + put32(req + p, 0); p += 4; // null buffer + put32(req + p, 0xFFFFFFFF); p += 4; // preferred maximum length + put32(req + p, 0x00020008); p += 4; // resume handle referent + put32(req + p, 0); p += 4; + + req[0] = 5; req[2] = 0x00; req[3] = 0x03; req[4] = 0x10; + put16(req + 8, (uint16_t)p); + put32(req + 12, 2); // call id + put32(req + 16, p - 24); // alloc hint + put16(req + 22, 15); // opnum NetrShareEnum + + n = pipe_transceive(c, tree, pipe, req, p, rpc, kRpcCap); + if (n < 0) { result = n; break; } + + // Join the stub data of all response fragments in place. + uint32_t stubLen = 0; + uint32_t pos = 0; + bool bad = false; + while (pos + 24 <= (uint32_t)n) { + uint32_t fragLen = get16(rpc + pos + 8); + uint32_t authLen = get16(rpc + pos + 10); + if (rpc[pos + 2] != 0x02 || fragLen < 24 || pos + fragLen > (uint32_t)n || + authLen > fragLen - 24) { bad = true; break; } + uint32_t dataLen = fragLen - 24 - authLen; + memmove(rpc + stubLen, rpc + pos + 24, dataLen); + stubLen += dataLen; + pos += fragLen; + } + if (bad || stubLen == 0) break; + + Ndr ndr{rpc, stubLen, 0, true}; + uint32_t level = ndr.u32(); + ndr.u32(); // union switch + uint32_t container = ndr.u32(); + if (!ndr.ok || level != 1 || container == 0) break; + uint32_t entries = ndr.u32(); + uint32_t array = ndr.u32(); + if (!ndr.ok) break; + if (entries == 0 || array == 0) { result = 0; break; } + uint32_t maxCount = ndr.u32(); + if (!ndr.ok || maxCount < entries || entries > (stubLen - ndr.pos) / 12) break; + + // Fixed parts first (name pointer, type, remark pointer), then the + // strings in the same order. + uint32_t fixed = ndr.pos; + ndr.pos += entries * 12; + int count = 0; + for (uint32_t i = 0; i < entries && ndr.ok; i++) { + const uint8_t* f = rpc + fixed + i * 12; + uint32_t namePtr = get32(f); + uint32_t type = get32(f + 4); + uint32_t remarkPtr = get32(f + 8); + ShareInfo info; + memset(&info, 0, sizeof(info)); + if (namePtr != 0) ndr.string(info.name, sizeof(info.name)); + if (remarkPtr != 0) ndr.string(info.comment, sizeof(info.comment)); + if (!ndr.ok) break; + info.type = type & 0x0FFFFFFF; + info.hidden = (type & 0x80000000u) != 0; + if (count < max) out[count++] = info; + } + if (!ndr.ok) break; + result = count; + } while (false); + + free(rpc); + if (c->connected) { + close(c, tree, pipe); + tree_disconnect(c, tree); + } + return result; + } + + // ========================================================================== + // URL parsing + // ========================================================================== + + bool parse_url(const char* text, Url* out) { + memset(out, 0, sizeof(*out)); + if (text == nullptr) return false; + const char* s = text; + while (*s == ' ') s++; + if ((s[0] == 's' || s[0] == 'S') && (s[1] == 'm' || s[1] == 'M') && + (s[2] == 'b' || s[2] == 'B') && s[3] == ':') s += 4; + while (*s == '/' || *s == '\\') s++; + + // Authority: [domain;]user@host[:port] + const char* end = s; + while (*end && *end != '/' && *end != '\\') end++; + const char* at = nullptr; + for (const char* q = s; q < end; q++) if (*q == '@') at = q; + const char* host = s; + if (at != nullptr) { + const char* semi = nullptr; + for (const char* q = s; q < at; q++) if (*q == ';') { semi = q; break; } + const char* user = s; + if (semi != nullptr) { + size_t n = (size_t)(semi - s); + if (n >= sizeof(out->domain)) n = sizeof(out->domain) - 1; + memcpy(out->domain, s, n); + user = semi + 1; + } + size_t n = (size_t)(at - user); + if (n >= sizeof(out->user)) n = sizeof(out->user) - 1; + memcpy(out->user, user, n); + host = at + 1; + } + const char* hostEnd = end; + for (const char* q = host; q < end; q++) { + if (*q == ':') { + hostEnd = q; + int port = 0; + for (const char* d = q + 1; d < end && *d >= '0' && *d <= '9'; d++) { + port = port * 10 + (*d - '0'); + if (port > 65535) { port = 0; break; } + } + out->port = port; + break; + } + } + size_t n = (size_t)(hostEnd - host); + if (n == 0) return false; + if (n >= sizeof(out->host)) n = sizeof(out->host) - 1; + memcpy(out->host, host, n); + + // Share, then the path below it. + s = end; + while (*s == '/' || *s == '\\') s++; + const char* shareEnd = s; + while (*shareEnd && *shareEnd != '/' && *shareEnd != '\\') shareEnd++; + n = (size_t)(shareEnd - s); + if (n >= sizeof(out->share)) n = sizeof(out->share) - 1; + memcpy(out->share, s, n); + + s = shareEnd; + while (*s == '/' || *s == '\\') s++; + size_t pn = 0; + for (; *s && pn + 1 < sizeof(out->path); s++) out->path[pn++] = (*s == '\\') ? '/' : *s; + while (pn > 0 && (out->path[pn - 1] == '/' || out->path[pn - 1] == ' ')) pn--; + out->path[pn] = '\0'; + return true; + } + +} diff --git a/programs/man/smb.1 b/programs/man/smb.1 new file mode 100644 index 0000000..63eb4fb --- /dev/null +++ b/programs/man/smb.1 @@ -0,0 +1,61 @@ +.TH SMB 1 +.SH NAME +smb \- list, mount and unmount SMB network shares +.SH SYNOPSIS +.B smb +.I command +.RI [ options ] +.SH DESCRIPTION +.B smb +connects to file servers that speak SMB 2 or SMB 3 (Windows, Samba, most NAS devices). +A mounted share becomes an ordinary drive, usable by every program. +Mounting is done by the +.BR smbfs (1) +helper, which keeps running for as long as the share is mounted. +.SH COMMANDS +.TP +.B shares \fI//host\fR +List the shares a server offers. +.TP +.B mount \fI//host/share\fR +Mount a share and print the drive it was given. +.TP +.B list +Show the shares that are mounted. +.TP +.B unmount \fIdrive\fR +Disconnect a mounted share, for example +.BR "smb unmount 32" . +.SH OPTIONS +.TP +.B \-\-user \fINAME\fR +Log on as NAME. Without a user name the guest account is tried. +.TP +.B \-\-domain \fINAME\fR +Domain or workgroup of the account. +.TP +.B \-\-password \fIPW\fR +Password. If omitted, the SMB_PASSWORD environment variable is used, and +otherwise you are asked for it. +.TP +.B \-\-port \fIN\fR +Server port (default 445). +.TP +.B \-\-label \fITEXT\fR +Drive label for a mounted share. +.TP +.B \-\-ro +Mount read-only. +.SH ADDRESSES +A share is written +.IR //host/share , +.I smb://host/share +or +.IR \e\ehost\eshare . +A user may be included as +.IR smb://user@host/share . +.SH LIMITS +SMB 1, Kerberos logons and SMB 3 encryption are not supported. A server or +share that insists on encryption is refused. +.SH SEE ALSO +.BR smbfs (1) diff --git a/programs/man/smbfs.1 b/programs/man/smbfs.1 new file mode 100644 index 0000000..d62cb9e --- /dev/null +++ b/programs/man/smbfs.1 @@ -0,0 +1,39 @@ +.TH SMBFS 1 +.SH NAME +smbfs \- provider process that serves a mounted SMB share +.SH SYNOPSIS +.B smbfs +.I //host/share +.RB [ \-\-user +.IR NAME ] +.RB [ \-\-domain +.IR NAME ] +.RB [ \-\-port +.IR N ] +.RB [ \-\-label +.IR TEXT ] +.RB [ \-\-ro ] +.SH DESCRIPTION +.B smbfs +logs on to an SMB server, registers a drive with the kernel and answers every +file operation made on that drive by talking SMB to the server. It is normally +started by Files or by +.BR smb (1) +rather than by hand. +.PP +The password is read from the SMB_PASSWORD environment variable so that it +never appears in an argument list. +.PP +On startup one status line is written to standard output: +.B OK +.I drive +when the share is mounted, or +.B ERR +.I status message +when it could not be. +.PP +The share stays mounted until the process exits. Ejecting the drive asks it to +close its files, log off and exit. If the connection drops it reconnects on the +next file operation. +.SH SEE ALSO +.BR smb (1) diff --git a/programs/src/files/Makefile b/programs/src/files/Makefile index 8267468..c9a1e6a 100644 --- a/programs/src/files/Makefile +++ b/programs/src/files/Makefile @@ -64,7 +64,7 @@ TARGET := $(BINDIR)/apps/files/files.elf all: $(TARGET) -LIBS := $(JPEG_LIB)/$(ARCH_OUT)libjpeg.a $(BEARSSL)/build$(ARCH_SUFFIX)/libbearssl.a $(LIBDIR)/libc/$(ARCH_OUT)liblibc.a +LIBS := $(LIBDIR)/smb/$(ARCH_OUT)libsmb.a $(JPEG_LIB)/$(ARCH_OUT)libjpeg.a $(BEARSSL)/build$(ARCH_SUFFIX)/libbearssl.a $(LIBDIR)/libc/$(ARCH_OUT)liblibc.a $(TARGET): $(OBJS) $(LINK_LD) Makefile $(LIBS) mkdir -p $(BINDIR)/apps/files diff --git a/programs/src/files/actions.cpp b/programs/src/files/actions.cpp index 6eccd3d..bd16931 100644 --- a/programs/src/files/actions.cpp +++ b/programs/src/files/actions.cpp @@ -451,7 +451,15 @@ void filemanager_open_ctx_menu(FileManagerState* fm, int local_x, int local_y, i int row = -2 - target_idx; if (row >= fm->sidebar_count) { fm->ctx_open = false; return; } const FileManagerSidebarItem& item = fm->sidebar_items[row]; + if (item.kind == FM_SIDEBAR_CONNECT) { + fm->ctx_items[fm->ctx_item_count++] = CTX_NET_CONNECT; + return; + } fm->ctx_items[fm->ctx_item_count++] = CTX_OPEN; + if (item.kind == FM_SIDEBAR_DRIVE && item.drive_kind == FM_DRIVE_KIND_NETWORK) + fm->ctx_items[fm->ctx_item_count++] = CTX_NET_DISCONNECT; + if (item.kind == FM_SIDEBAR_NETSHARE) + fm->ctx_items[fm->ctx_item_count++] = CTX_NET_FORGET; if (item.kind == FM_SIDEBAR_TRASH && filemanager_trash_has_items(fm->desktop)) fm->ctx_items[fm->ctx_item_count++] = CTX_EMPTY_TRASH; if (item.bookmark) diff --git a/programs/src/files/events.cpp b/programs/src/files/events.cpp index 9135a68..92103db 100644 --- a/programs/src/files/events.cpp +++ b/programs/src/files/events.cpp @@ -204,6 +204,11 @@ void filemanager_on_mouse(Window* win, MouseEvent& ev) { if (row < fm->sidebar_count) { if (action == CTX_OPEN) filemanager_sidebar_open(fm, row); else if (action == CTX_EMPTY_TRASH) filemanager_show_empty_trash_confirmation(fm); + else if (action == CTX_NET_CONNECT) filemanager_net_show_connect(fm, -1); + else if (action == CTX_NET_DISCONNECT) + filemanager_net_disconnect(fm, fm->sidebar_items[row].drive); + else if (action == CTX_NET_FORGET) + filemanager_net_forget(fm, fm->sidebar_items[row].net_index); else if (action == CTX_REMOVE_BOOKMARK) { char path[256]; montauk::strncpy(path, fm->sidebar_items[row].path, sizeof(path)); @@ -689,6 +694,7 @@ void filemanager_on_poll(Window* win) { if (!fm) return; if (filemanager_thumbs_poll(fm)) win->dirty = true; filemanager_dnd_poll(fm); + filemanager_net_poll(fm); } void filemanager_on_close(Window* win) { diff --git a/programs/src/files/filemanager_internal.hpp b/programs/src/files/filemanager_internal.hpp index c757790..d8e622f 100644 --- a/programs/src/files/filemanager_internal.hpp +++ b/programs/src/files/filemanager_internal.hpp @@ -72,13 +72,20 @@ enum FileManagerSidebarKind : uint8_t { FM_SIDEBAR_FOLDER, // home, a standard folder or a bookmark FM_SIDEBAR_TRASH, FM_SIDEBAR_DRIVE, + FM_SIDEBAR_NETSHARE, // saved network share that is not mounted (network.cpp) + FM_SIDEBAR_CONNECT, // "Connect to Server..." }; +// SYS_DRIVEKIND value of a provider-backed network drive (DRIVE_KIND_NETWORK). +inline constexpr int FM_DRIVE_KIND_NETWORK = 6; + struct FileManagerSidebarItem { FileManagerSidebarKind kind; bool bookmark; // removable (user bookmark) int special_index; // standard folder index, -1 otherwise int drive_kind; // FM_SIDEBAR_DRIVE: kernel BlockDeviceKind + int drive; // FM_SIDEBAR_DRIVE: drive number + int net_index; // FM_SIDEBAR_NETSHARE: saved share index char label[64]; char path[256]; // empty for Computer / Trash / headers }; @@ -190,6 +197,7 @@ struct FileManagerState { // File Manager-owned dialogs void* delete_confirm_dialog; void* open_with_dialog; + void* connect_dialog; // "Connect to Server" (network.cpp) // No window of its own (files.elf --transfer / --open-with). bool headless; @@ -376,6 +384,9 @@ inline constexpr int CTX_REMOVE_BOOKMARK = 20; // "Remove from Sidebar" inline constexpr int CTX_UNDO = 21; inline constexpr int CTX_REDO = 22; inline constexpr int CTX_NEW = 23; // opens the "New" submenu +inline constexpr int CTX_NET_DISCONNECT = 24; // eject a mounted network share +inline constexpr int CTX_NET_FORGET = 25; // drop a saved network share +inline constexpr int CTX_NET_CONNECT = 26; // "Connect to Server..." inline constexpr int CTX_NEW_FILE_BASE = 32; // + template index (newfile.cpp) inline bool filemanager_is_virtual_view(const FileManagerState* fm) { @@ -504,8 +515,23 @@ montauk::StatusCode filemanager_delete_recursive(const char* path); // Permanent delete that also drops the Trash info file when path is a // top-level Trash item. Use this for user-initiated deletes. montauk::StatusCode filemanager_delete_item(const char* path); -montauk::StatusCode filemanager_copy_file(const char* src, const char* dst); -montauk::StatusCode filemanager_copy_dir_recursive(const char* src, const char* dst); +// Progress hooks for long copies (the file operation worker). Every member is +// optional. A cancelled copy stops at the next chunk, deletes the partial +// file and returns a failure status. +struct FileCopyProgress { + void (*file_begin)(void* ctx, const char* path); // before each file + void (*bytes)(void* ctx, uint64_t n); // after each chunk + bool (*cancelled)(void* ctx); + void* ctx; +}; +montauk::StatusCode filemanager_copy_file(const char* src, const char* dst, + FileCopyProgress* progress = nullptr); +montauk::StatusCode filemanager_copy_dir_recursive(const char* src, const char* dst, + FileCopyProgress* progress = nullptr); +// Add up the files and bytes under `path` (a file counts as one). Stops early +// once *cancel becomes non-zero. +void filemanager_measure_tree(const char* path, uint64_t* bytes, int* files, + volatile int* cancel); // Clipboard (actions.cpp). Copy and cut publish TRANSFER_MIME_FILE_LIST, // TRANSFER_MIME_FILE_OP ("copy"/"cut") and the paths as plain text. @@ -607,6 +633,24 @@ void filemanager_sidebar_open(FileManagerState* fm, int idx); // Folder a sidebar row stands for, for drops ("" for Computer/headers). bool filemanager_sidebar_target_path(FileManagerState* fm, int idx, char* out, int out_max); +// ---- Network shares (network.cpp) ---- +// Saved shares live in /config/network.toml; mounting is done by the +// smbfs.elf provider, after which a share is an ordinary drive. +void filemanager_net_load(DesktopState* ds); +int filemanager_net_share_count(); +bool filemanager_net_share(int i, char* label, int label_max, int* mounted_drive); +// 16px / 48px icon of a network drive; null if the icon is missing. +const SvgIcon* filemanager_net_drive_icon(bool large); +const SvgIcon* filemanager_net_connect_icon(); +// Open the Connect to Server dialog, prefilled from a saved share (-1 = empty). +void filemanager_net_show_connect(FileManagerState* fm, int saved_index); +// Go to a saved share, connecting first if it is not mounted. +void filemanager_net_open_saved(FileManagerState* fm, int saved_index); +void filemanager_net_disconnect(FileManagerState* fm, int drive); +void filemanager_net_forget(FileManagerState* fm, int saved_index); +// Follow drives appearing and disappearing (called from the window's poll). +void filemanager_net_poll(FileManagerState* fm); + // ---- New files (newfile.cpp) ---- const char* filemanager_new_file_label(int action); // Fill ctx_sub_items: Folder, then the document types some app can open. diff --git a/programs/src/files/fileop.cpp b/programs/src/files/fileop.cpp index b9e962a..c7dccf1 100644 --- a/programs/src/files/fileop.cpp +++ b/programs/src/files/fileop.cpp @@ -46,11 +46,28 @@ struct FileOpJob { FileManagerState* owner; // for the post-op refresh (liveness-checked) Color accent; - volatile int files_total; + volatile int files_total; // top-level items volatile int files_done; volatile int cancel; // UI -> worker volatile int finished; // worker -> UI volatile char current[128]; // basename of the item in progress (worker writes) + volatile int current_seq; // bumped after each change to `current` + + // Copy/move progress across every file inside the items, measured by a + // scan before the copy starts (worker writes, dialog reads). + volatile int scanning; + volatile uint64_t bytes_total; + volatile uint64_t bytes_done; + volatile int copy_files_total; + volatile int copy_files_done; // files started so far + + // Worker only: what the scan found per item, and the totals of the + // finished items. Each finished item resets the live counters to these, + // so skipped items and instant renames still move the bar. + uint64_t* item_bytes; + int* item_files; + uint64_t base_bytes; + int base_files; // Failures, written by the worker and read on the UI thread only after // the worker has finished (joined), so they need no synchronization. @@ -73,6 +90,10 @@ struct FileOpJob { int tid; int last_drawn_done; // dialog redraw tracking int last_drawn_pending; + int last_drawn_seq; + int last_drawn_scanning; + uint64_t last_drawn_bytes; + uint64_t last_draw_ms; int mouse_x, mouse_y; }; @@ -96,6 +117,86 @@ static void fileop_set_current(FileOpJob* job, const char* name) { int i = 0; for (; name[i] && i < 127; i++) job->current[i] = name[i]; job->current[i] = '\0'; + job->current_seq = job->current_seq + 1; +} + +// Drive number of a "N:/..." path, or -1. +static int fileop_path_drive(const char* path) { + if (!path || path[0] < '0' || path[0] > '9') return -1; + int drive = 0; + int i = 0; + for (; path[i] >= '0' && path[i] <= '9'; i++) drive = drive * 10 + (path[i] - '0'); + return path[i] == ':' ? drive : -1; +} + +static bool fileop_path_is_network(const char* path) { + int drive = fileop_path_drive(path); + return drive >= 0 && montauk::drivekind(drive) == FM_DRIVE_KIND_NETWORK; +} + +// Copy progress hooks (worker thread). +static void fileop_progress_file_begin(void* ctx, const char* path) { + FileOpJob* job = (FileOpJob*)ctx; + fileop_set_current(job, path_basename(path)); + job->copy_files_done = job->copy_files_done + 1; +} + +static void fileop_progress_bytes(void* ctx, uint64_t n) { + FileOpJob* job = (FileOpJob*)ctx; + job->bytes_done = job->bytes_done + n; +} + +static bool fileop_progress_cancelled(void* ctx) { + return ((FileOpJob*)ctx)->cancel != 0; +} + +// Item `i` is finished (done, skipped or failed). +static void fileop_item_done(FileOpJob* job, int i) { + if (job->item_bytes && job->item_files) { + job->base_bytes += job->item_bytes[i]; + job->base_files += job->item_files[i]; + job->bytes_done = job->base_bytes; + job->copy_files_done = job->base_files; + } + job->files_done = i + 1; +} + +// Measure every item before copying so the dialog can show files and bytes +// for the whole operation, not just how many top-level items are done. A move +// within one drive is a rename and copies nothing, so it is not measured. +static void fileop_scan(FileOpJob* job) { + job->item_bytes = (uint64_t*)montauk::malloc((uint64_t)job->count * sizeof(uint64_t)); + job->item_files = (int*)montauk::malloc((uint64_t)job->count * sizeof(int)); + if (!job->item_bytes || !job->item_files) { + montauk::mfree(job->item_bytes); + montauk::mfree(job->item_files); + job->item_bytes = nullptr; + job->item_files = nullptr; + return; + } + + job->scanning = 1; + uint64_t total_bytes = 0; + int total_files = 0; + for (int i = 0; i < job->count; i++) { + uint64_t bytes = 0; + int files = 0; + const char* src = job->paths[i]; + const char* dest = job->dests ? job->dests[i] : job->dest_dir; + bool rename_only = job->kind == FILE_OP_MOVE && + fileop_path_drive(src) == fileop_path_drive(dest); + if (!job->cancel && !rename_only) { + fileop_set_current(job, path_basename(src)); + filemanager_measure_tree(src, &bytes, &files, &job->cancel); + } + job->item_bytes[i] = bytes; + job->item_files[i] = files; + total_bytes += bytes; + total_files += files; + job->bytes_total = total_bytes; + job->copy_files_total = total_files; + } + job->scanning = 0; } static const char* fileop_error_verb(int kind) { @@ -172,6 +273,9 @@ static int fileop_resolve_conflict(FileOpJob* job, const char* name, static int fileop_worker(void* arg) { FileOpJob* job = (FileOpJob*)arg; + if (job->kind == FILE_OP_COPY || job->kind == FILE_OP_MOVE) fileop_scan(job); + FileCopyProgress progress = { fileop_progress_file_begin, fileop_progress_bytes, + fileop_progress_cancelled, job }; for (int i = 0; i < job->count && !job->cancel; i++) { const char* src = job->paths[i]; @@ -180,14 +284,14 @@ static int fileop_worker(void* arg) { if (job->kind == FILE_OP_DELETE) { fileop_record_status(job, src, filemanager_delete_item(src)); - job->files_done = i + 1; + fileop_item_done(job, i); continue; } if (job->kind == FILE_OP_TRASH) { montauk::StatusCode st = filemanager_trash_item(job->desktop, src, job->done_paths[i], 256); job->done_ok[i] = job->done_new[i] = st == montauk::Success; fileop_record_status(job, src, st); - job->files_done = i + 1; + fileop_item_done(job, i); continue; } @@ -196,7 +300,7 @@ static int fileop_worker(void* arg) { if (is_dir && fileop_path_same_or_descendant(job->dest_dir, src)) { // Refuse to copy a directory into itself. fileop_record_status(job, src, montauk::InvalidArgument); - job->files_done = i + 1; + fileop_item_done(job, i); continue; } @@ -206,18 +310,18 @@ static int fileop_worker(void* arg) { montauk::strncpy(dst, job->dests[i], sizeof(dst)); if (filemanager_path_exists(dst)) { fileop_record_status(job, dst, montauk::AlreadyExists); - job->files_done = i + 1; + fileop_item_done(job, i); continue; } } else { filemanager_build_fullpath(dst, 512, job->dest_dir, base); if (montauk::streq(dst, src)) { // Moving into its own folder is a no-op; copying duplicates it. - if (job->kind == FILE_OP_MOVE) { job->files_done = i + 1; continue; } + if (job->kind == FILE_OP_MOVE) { fileop_item_done(job, i); continue; } filemanager_unique_path(job->dest_dir, base, is_dir, true, dst, sizeof(dst)); } else if (filemanager_path_exists(dst)) { int choice = fileop_resolve_conflict(job, base, is_dir, filemanager_path_is_dir(dst)); - if (job->cancel || choice == FILEOP_CHOICE_SKIP) { job->files_done = i + 1; continue; } + if (job->cancel || choice == FILEOP_CHOICE_SKIP) { fileop_item_done(job, i); continue; } if (choice == FILEOP_CHOICE_KEEP_BOTH) filemanager_unique_path(job->dest_dir, base, is_dir, false, dst, sizeof(dst)); else @@ -234,8 +338,8 @@ static int fileop_worker(void* arg) { status = filemanager_status_from_result(montauk::frename(src, dst)); if (status != montauk::Success && !filemanager_status_is_access_denied(status)) { // Cross-volume (or driver without rename): fall back to copy + delete. - status = is_dir ? filemanager_copy_dir_recursive(src, dst) - : filemanager_copy_file(src, dst); + status = is_dir ? filemanager_copy_dir_recursive(src, dst, &progress) + : filemanager_copy_file(src, dst, &progress); if (status == montauk::Success) { status = is_dir ? filemanager_delete_recursive(src) @@ -243,18 +347,24 @@ static int fileop_worker(void* arg) { } } } else { // FILE_OP_COPY - status = is_dir ? filemanager_copy_dir_recursive(src, dst) - : filemanager_copy_file(src, dst); + status = is_dir ? filemanager_copy_dir_recursive(src, dst, &progress) + : filemanager_copy_file(src, dst, &progress); } - fileop_record_status(job, src, status); + // A copy stopped by Cancel fails on purpose; that is not an error to report. + if (!(job->cancel && status != montauk::Success)) + fileop_record_status(job, src, status); if (status == montauk::Success) { montauk::strncpy(job->done_paths[i], dst, 256); job->done_ok[i] = true; job->done_new[i] = !replacing; } - job->files_done = i + 1; + fileop_item_done(job, i); } + montauk::mfree(job->item_bytes); + montauk::mfree(job->item_files); + job->item_bytes = nullptr; + job->item_files = nullptr; job->finished = 1; return 0; } @@ -393,16 +503,50 @@ static void fileop_dialog_on_draw(Window* win, Framebuffer& fb) { int fh = system_font_height(); int y = 18; - // Title: "Copying 3 of 12" + // Copies and moves count every file inside the items (from the scan) and + // fill the bar by bytes; deletes count top-level items. + bool scanning = job->scanning != 0; + uint64_t bytes_total = job->bytes_total; + uint64_t bytes_done = job->bytes_done; + if (bytes_done > bytes_total) bytes_done = bytes_total; + bool by_files = (job->kind == FILE_OP_COPY || job->kind == FILE_OP_MOVE) && + job->copy_files_total > 0; + + // Title: "Copying 3 of 12", or "Preparing to copy..." while scanning. char title[96]; - int done = job->files_done; - int total = job->files_total; - if (total > 1) - snprintf(title, sizeof(title), "%s %d of %d", fileop_verb(job->kind), - done < total ? done + 1 : total, total); - else + int done = by_files ? job->copy_files_done : job->files_done; + int total = by_files ? job->copy_files_total : job->files_total; + if (scanning) { + snprintf(title, sizeof(title), "Preparing to %s...", fileop_error_verb(job->kind)); + } else if (total > 1) { + // by_files counts files started (the current one included); the item + // count is items finished, so the current one is the next. + int shown = by_files ? done : done + 1; + if (shown < 1) shown = 1; + if (shown > total) shown = total; + snprintf(title, sizeof(title), "%s %d of %d", fileop_verb(job->kind), shown, total); + } else { snprintf(title, sizeof(title), "%s...", fileop_verb(job->kind)); + } c.text(pad, y, title, theme.text); + + // Right side of the title row: "12.3 MB of 450 MB" (or the running count + // while scanning). + char amount[64] = ""; + if (scanning) { + int files = job->copy_files_total; + if (files > 0) snprintf(amount, sizeof(amount), "%d file%s", files, files == 1 ? "" : "s"); + } else if (bytes_total > 0) { + char a[16], b[16]; + format_size(a, bytes_done); + format_size(b, bytes_total); + snprintf(amount, sizeof(amount), "%s of %s", a, b); + } + if (amount[0]) { + int aw = text_width(amount); + if (pad + text_width(title) + 16 + aw <= c.w - pad) + c.text(c.w - pad - aw, y, amount, theme.text_muted); + } y += fh + 10; // Current item name (copied out of the volatile buffer). @@ -424,9 +568,19 @@ static void fileop_dialog_on_draw(Window* win, Framebuffer& fb) { c.fill_rounded_rect(bar_x, y, bar_w, bar_h, 5, Color::from_rgb(0xE0, 0xE0, 0xE0)); int frac_w = 0; - if (total > 0) { - if (done > total) done = total; - frac_w = (int)(((int64_t)bar_w * done) / total); + if (scanning) { + frac_w = 0; + } else if (by_files && bytes_total > 0) { + // Scale down so bar_w * bytes stays within 64 bits. + uint64_t t = bytes_total, d = bytes_done; + while (t > (1ull << 40)) { t >>= 1; d >>= 1; } + frac_w = (int)(((uint64_t)bar_w * d) / t); + } else if (total > 0) { + // By files: count only finished ones (done includes the current file). + int finished = by_files ? done - 1 : done; + if (finished < 0) finished = 0; + if (finished > total) finished = total; + frac_w = (int)(((int64_t)bar_w * finished) / total); } if (frac_w > 0) c.fill_rounded_rect(bar_x, y, frac_w, bar_h, 5, job->accent); @@ -510,6 +664,23 @@ static void fileop_dialog_on_poll(Window* win) { job->last_drawn_pending = pending; win->dirty = true; } + int scanning = job->scanning; + if (scanning != job->last_drawn_scanning) { + job->last_drawn_scanning = scanning; + win->dirty = true; + } + // Byte counts and file names change constantly; ten redraws a second is plenty. + int seq = job->current_seq; + uint64_t bytes = job->bytes_done; + if (seq != job->last_drawn_seq || bytes != job->last_drawn_bytes) { + uint64_t now = montauk::get_milliseconds(); + if (now - job->last_draw_ms >= 100) { + job->last_drawn_seq = seq; + job->last_drawn_bytes = bytes; + job->last_draw_ms = now; + win->dirty = true; + } + } if (job->finished) { // Hand off to on_close, which joins the worker, refreshes the file @@ -687,7 +858,10 @@ bool filemanager_start_transfer(FileManagerState* fm, bool move, const char* con int count, const char* dest_dir) { if (!fm || fm->active_fileop || !paths || count <= 0 || !dest_dir || !dest_dir[0]) return false; - if (count == 1 && !filemanager_path_is_dir(paths[0])) { + // A network drive moves a 16 MiB file slowly enough to freeze the window, + // so those always get the worker and the dialog. + if (count == 1 && !filemanager_path_is_dir(paths[0]) && + !fileop_path_is_network(paths[0]) && !fileop_path_is_network(dest_dir)) { const char* src = paths[0]; uint64_t sz = 0; int fd = montauk::open(src); diff --git a/programs/src/files/filesystem.cpp b/programs/src/files/filesystem.cpp index a71267a..cd19c9a 100644 --- a/programs/src/files/filesystem.cpp +++ b/programs/src/files/filesystem.cpp @@ -585,6 +585,50 @@ static int filemanager_read_all_children(const char* dir, char (**out)[256]) { return count; } +static uint64_t filemanager_file_size(const char* path) { + montauk::abi::FileStat st; + if (montauk::stat(path, &st) == 0) return st.size; + // Not every driver implements stat. + uint64_t size = 0; + int fd = montauk::open(path); + if (fd >= 0) { size = montauk::getsize(fd); montauk::close(fd); } + return size; +} + +static void filemanager_measure_children(const char* dir, uint64_t* bytes, int* files, + volatile int* cancel) { + char (*children)[256] = nullptr; + int count = filemanager_read_all_children(dir, &children); + for (int i = 0; i < count && !(cancel && *cancel); i++) { + char basename[256]; + montauk::strncpy(basename, children[i], 255); + basename[255] = '\0'; + int blen = montauk::slen(basename); + bool child_is_dir = blen > 0 && basename[blen - 1] == '/'; + if (child_is_dir) basename[blen - 1] = '\0'; + + char child[512]; + filemanager_build_fullpath(child, 512, dir, basename); + if (child_is_dir) { + filemanager_measure_children(child, bytes, files, cancel); + } else { + *bytes += filemanager_file_size(child); + (*files)++; + } + } + if (children) montauk::mfree(children); +} + +void filemanager_measure_tree(const char* path, uint64_t* bytes, int* files, + volatile int* cancel) { + if (filemanager_path_is_dir(path)) { + filemanager_measure_children(path, bytes, files, cancel); + } else { + *bytes += filemanager_file_size(path); + (*files)++; + } +} + montauk::StatusCode filemanager_delete_recursive(const char* path) { // Try deleting as a file (or empty directory) first montauk::StatusCode status = filemanager_status_from_result(montauk::fdelete(path)); @@ -624,8 +668,10 @@ montauk::StatusCode filemanager_delete_recursive(const char* path) { return status; } -montauk::StatusCode filemanager_copy_file(const char* src, const char* dst) { +montauk::StatusCode filemanager_copy_file(const char* src, const char* dst, + FileCopyProgress* progress) { if (!src || !dst || montauk::streq(src, dst)) return montauk::InvalidArgument; + if (progress && progress->file_begin) progress->file_begin(progress->ctx, src); // A folder cannot be replaced by a file (rename would even delete an empty // one), so refuse rather than guess. @@ -675,6 +721,10 @@ montauk::StatusCode filemanager_copy_file(const char* src, const char* dst) { uint64_t off = 0; while (off < size) { + if (progress && progress->cancelled && progress->cancelled(progress->ctx)) { + status = montauk::GenericFailure; + break; + } uint64_t todo64 = size - off; if (todo64 > buf_size) todo64 = buf_size; int todo = (int)todo64; @@ -689,6 +739,7 @@ montauk::StatusCode filemanager_copy_file(const char* src, const char* dst) { break; } off += todo64; + if (progress && progress->bytes) progress->bytes(progress->ctx, todo64); } montauk::mfree(buf); @@ -704,7 +755,8 @@ montauk::StatusCode filemanager_copy_file(const char* src, const char* dst) { } // Recursive directory copy -montauk::StatusCode filemanager_copy_dir_recursive(const char* src, const char* dst) { +montauk::StatusCode filemanager_copy_dir_recursive(const char* src, const char* dst, + FileCopyProgress* progress) { if (!src || !dst || montauk::streq(src, dst)) return montauk::InvalidArgument; // Ignore the result: the destination may already exist (merge). If it @@ -717,6 +769,10 @@ montauk::StatusCode filemanager_copy_dir_recursive(const char* src, const char* montauk::StatusCode status = montauk::Success; for (int i = 0; i < count; i++) { + if (progress && progress->cancelled && progress->cancelled(progress->ctx)) { + if (status == montauk::Success) status = montauk::GenericFailure; + break; + } bool child_is_dir = false; char basename[256]; montauk::strncpy(basename, children[i], 255); @@ -732,8 +788,8 @@ montauk::StatusCode filemanager_copy_dir_recursive(const char* src, const char* filemanager_build_fullpath(dst_child, 512, dst, basename); montauk::StatusCode s = child_is_dir - ? filemanager_copy_dir_recursive(src_child, dst_child) - : filemanager_copy_file(src_child, dst_child); + ? filemanager_copy_dir_recursive(src_child, dst_child, progress) + : filemanager_copy_file(src_child, dst_child, progress); if (s != montauk::Success && status == montauk::Success) status = s; } diff --git a/programs/src/files/helpers.cpp b/programs/src/files/helpers.cpp index b3a2f47..9bf9510 100644 --- a/programs/src/files/helpers.cpp +++ b/programs/src/files/helpers.cpp @@ -147,6 +147,9 @@ const char* ctx_label(int action) { case CTX_UNDO: return "Undo"; case CTX_REDO: return "Redo"; case CTX_NEW: return "New"; + case CTX_NET_DISCONNECT: return "Disconnect"; + case CTX_NET_FORGET: return "Forget Share"; + case CTX_NET_CONNECT: return "Connect to Server..."; default: return action >= CTX_NEW_FILE_BASE ? filemanager_new_file_label(action) : "?"; } @@ -213,7 +216,9 @@ int ctx_group(int action) { case CTX_UNDO: case CTX_REDO: return 7; case CTX_ADD_BOOKMARK: - case CTX_REMOVE_BOOKMARK: return 8; + case CTX_REMOVE_BOOKMARK: + case CTX_NET_DISCONNECT: + case CTX_NET_FORGET: return 8; case CTX_SELECT_ALL: case CTX_TOGGLE_HIDDEN: return 3; case CTX_SORT_NAME: diff --git a/programs/src/files/network.cpp b/programs/src/files/network.cpp new file mode 100644 index 0000000..f90dce1 --- /dev/null +++ b/programs/src/files/network.cpp @@ -0,0 +1,961 @@ +/* + * network.cpp + * Network shares in Files: the saved SMB shares, the "Connect to Server" + * dialog and mounting / disconnecting shares + * Copyright (c) 2026 Daniel Hammer +*/ + +#include "filemanager_internal.hpp" +#include +#include +#include +#include +#include +#include + +// A share is mounted by the smbfs.elf provider (src/smbfs), which makes it an +// ordinary drive: once mounted, nothing in Files treats it specially beyond +// the icon and the Disconnect action. This file only decides what to mount. +// +// Shares the user connected to are remembered in /config/network.toml: +// [shares] +// list = ["host|share|user|domain|port||label", ...] +// The password is present only when "Remember password" was ticked. It is +// hex-encoded so any character survives the record format, NOT encrypted: +// anyone who can read the user's config directory can read it. + +namespace filemanager { + +static constexpr const char* NET_CONFIG = "network"; +static constexpr int NET_MAX_SHARES = 32; + +struct NetShare { + char host[128]; + char share[128]; + char user[96]; + char domain[64]; + char label[64]; + char password[128]; + bool has_password; + int port; +}; + +static NetShare g_shares[NET_MAX_SHARES]; +static int g_share_count = 0; + +static SvgIcon g_icon_server; +static SvgIcon g_icon_server_lg; +static SvgIcon g_icon_network; + +static void net_load_icons() { + if (g_icon_server.pixels) return; + Color def = colors::ICON_COLOR; + g_icon_server = svg_load("0:/os/icons/network-server.svg", 16, 16, def); + g_icon_server_lg = svg_load("0:/os/icons/network-server.svg", 48, 48, def); + g_icon_network = svg_load("0:/os/icons/network-workgroup.svg", 16, 16, def); +} + +const SvgIcon* filemanager_net_drive_icon(bool large) { + net_load_icons(); + const SvgIcon* icon = large ? &g_icon_server_lg : &g_icon_server; + return icon->pixels ? icon : nullptr; +} + +const SvgIcon* filemanager_net_connect_icon() { + net_load_icons(); + return g_icon_network.pixels ? &g_icon_network : nullptr; +} + +// ============================================================================ +// Saved shares +// ============================================================================ + +static bool eq_nocase(const char* a, const char* b) { + for (; *a && *b; a++, b++) { + char ca = (*a >= 'A' && *a <= 'Z') ? (char)(*a + 32) : *a; + char cb = (*b >= 'A' && *b <= 'Z') ? (char)(*b + 32) : *b; + if (ca != cb) return false; + } + return *a == *b; +} + +static void hex_encode(const char* in, char* out, int out_max) { + static const char digits[] = "0123456789abcdef"; + int n = 0; + for (; *in && n + 2 < out_max; in++) { + out[n++] = digits[((unsigned char)*in) >> 4]; + out[n++] = digits[((unsigned char)*in) & 0xF]; + } + out[n] = '\0'; +} + +static int hex_digit(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + return -1; +} + +static void hex_decode(const char* in, int len, char* out, int out_max) { + int n = 0; + for (int i = 0; i + 1 < len && n + 1 < out_max; i += 2) { + int hi = hex_digit(in[i]); + int lo = hex_digit(in[i + 1]); + if (hi < 0 || lo < 0) break; + out[n++] = (char)((hi << 4) | lo); + } + out[n] = '\0'; +} + +// Copy the next '|'-separated field of *cursor into out; false at the end. +static bool next_field(const char** cursor, char* out, int out_max) { + const char* s = *cursor; + if (s == nullptr) return false; + int n = 0; + while (*s && *s != '|') { + if (n + 1 < out_max) out[n++] = *s; + s++; + } + out[n] = '\0'; + *cursor = *s == '|' ? s + 1 : nullptr; + return true; +} + +static bool parse_share(const char* rec, NetShare* out) { + montauk::memset(out, 0, sizeof(*out)); + const char* cur = rec; + char port[16]; + char pwhex[300]; + if (!next_field(&cur, out->host, sizeof(out->host)) || + !next_field(&cur, out->share, sizeof(out->share)) || + !next_field(&cur, out->user, sizeof(out->user)) || + !next_field(&cur, out->domain, sizeof(out->domain)) || + !next_field(&cur, port, sizeof(port)) || + !next_field(&cur, pwhex, sizeof(pwhex))) return false; + // The label is last so it may contain the separator. + if (cur) montauk::strncpy(out->label, cur, sizeof(out->label)); + out->port = atoi(port); + out->has_password = pwhex[0] != '\0'; + hex_decode(pwhex, montauk::slen(pwhex), out->password, sizeof(out->password)); + return out->host[0] && out->share[0]; +} + +static void net_read(DesktopState* ds) { + g_share_count = 0; + if (!ds || !ds->current_user[0]) return; + montauk::toml::Doc doc = montauk::config::load_user(ds->current_user, NET_CONFIG); + if (auto* arr = doc.get_array("shares.list")) { + for (int i = 0; i < arr->array.count && g_share_count < NET_MAX_SHARES; i++) { + auto* v = arr->array.items[i]; + if (v->type != montauk::toml::Type::String) continue; + if (parse_share(v->str, &g_shares[g_share_count])) g_share_count++; + } + } + doc.destroy(); +} + +static void net_write(DesktopState* ds) { + if (!ds || !ds->current_user[0]) return; + montauk::toml::Doc doc; + doc.init(); + auto* arr = montauk::toml::Value::make_array("shares.list"); + for (int i = 0; i < g_share_count; i++) { + const NetShare& s = g_shares[i]; + char pwhex[300] = ""; + if (s.has_password) hex_encode(s.password, pwhex, sizeof(pwhex)); + char rec[900]; + snprintf(rec, sizeof(rec), "%s|%s|%s|%s|%d|%s|%s", s.host, s.share, s.user, s.domain, + s.port, pwhex, s.label); + arr->array.push(montauk::toml::Value::make_string(nullptr, rec, montauk::slen(rec))); + } + doc.entries.push(arr); + montauk::config::ensure_user_dir(ds->current_user); + montauk::config::save_user(ds->current_user, NET_CONFIG, &doc); + doc.destroy(); +} + +static int net_find(const char* host, const char* share) { + for (int i = 0; i < g_share_count; i++) { + if (eq_nocase(g_shares[i].host, host) && eq_nocase(g_shares[i].share, share)) return i; + } + return -1; +} + +// Remember a share that was just mounted (most recent first). Re-reads the +// file first so several Files windows do not undo one another's edits. +static void net_remember(DesktopState* ds, const NetShare& share) { + net_read(ds); + int at = net_find(share.host, share.share); + if (at < 0) { + if (g_share_count == NET_MAX_SHARES) g_share_count--; + at = g_share_count++; + } + for (int i = at; i > 0; i--) g_shares[i] = g_shares[i - 1]; + g_shares[0] = share; + net_write(ds); +} + +static void net_forget(DesktopState* ds, const char* host, const char* share) { + net_read(ds); + int at = net_find(host, share); + if (at < 0) return; + for (int i = at; i + 1 < g_share_count; i++) g_shares[i] = g_shares[i + 1]; + g_share_count--; + net_write(ds); +} + +void filemanager_net_load(DesktopState* ds) { + net_read(ds); +} + +int filemanager_net_share_count() { + return g_share_count; +} + +// Sidebar label of saved share i, and (optionally) the drive it is mounted on. +bool filemanager_net_share(int i, char* label, int label_max, int* mounted_drive) { + if (i < 0 || i >= g_share_count) return false; + const NetShare& s = g_shares[i]; + if (label) { + if (s.label[0]) snprintf(label, (size_t)label_max, "%s", s.label); + else snprintf(label, (size_t)label_max, "%s on %s", s.share, s.host); + } + if (mounted_drive) *mounted_drive = smb::find_mount(s.host, s.share); + return true; +} + +// ============================================================================ +// Drive watching +// ============================================================================ + +// Shares are mounted and ejected by other processes, so notice drives coming +// and going: refresh the sidebar, and leave a folder whose drive vanished. +void filemanager_net_poll(FileManagerState* fm) { + static uint64_t last_check = 0; + static uint64_t last_signature = 0; + uint64_t now = montauk::get_milliseconds(); + if (now - last_check < 1000) return; + last_check = now; + + int drives[FM_MAX_DRIVES]; + int n = montauk::drivelist(drives, FM_MAX_DRIVES); + uint64_t signature = (uint64_t)n; + for (int i = 0; i < n; i++) signature = signature * 1099511628211ULL + (uint64_t)(drives[i] + 1); + if (signature == last_signature) return; + bool first = last_signature == 0; + last_signature = signature; + if (first) return; + + filemanager_sidebar_rebuild(fm); + if (filemanager_is_computer_view(fm)) { + filemanager_refresh(fm); + } else if (!filemanager_is_virtual_view(fm)) { + int current = atoi(fm->current_path); + bool present = false; + for (int i = 0; i < n; i++) present = present || drives[i] == current; + if (!present) filemanager_go_home(fm); + } +} + +void filemanager_net_disconnect(FileManagerState* fm, int drive) { + montauk::abi::UserFsInfo info; + if (montauk::userfs_info(drive, &info) != 0) return; + // Step out of the share first so nothing of ours keeps reading it. + if (!filemanager_is_computer_view(fm) && !filemanager_is_virtual_view(fm) && + atoi(fm->current_path) == drive) { + filemanager_go_home(fm); + } + if (smb::unmount(drive) != 0) { + filemanager_show_error(fm->desktop, fm, "Couldn't disconnect the share", info.source, + montauk::PermissionDenied); + } +} + +void filemanager_net_forget(FileManagerState* fm, int saved_index) { + if (saved_index < 0 || saved_index >= g_share_count) return; + char host[128]; + char share[128]; + montauk::strncpy(host, g_shares[saved_index].host, sizeof(host)); + montauk::strncpy(share, g_shares[saved_index].share, sizeof(share)); + net_forget(fm->desktop, host, share); + filemanager_sidebar_rebuild(fm); +} + +// ============================================================================ +// Share browsing (worker thread) +// ============================================================================ + +static constexpr int BROWSE_MAX = 64; + +struct BrowseJob { + // Two owners, the dialog and the worker; whoever lets go last frees it. + int refs; + volatile int done; + int tid; + char host[128]; + char user[96]; + char domain[64]; + char password[128]; + int port; + int count; // shares found, or a negative smb::Status + char names[BROWSE_MAX][96]; + char comments[BROWSE_MAX][64]; +}; + +static void browse_release(BrowseJob* job) { + if (__atomic_sub_fetch(&job->refs, 1, __ATOMIC_ACQ_REL) == 0) { + montauk::memset(job->password, 0, sizeof(job->password)); + montauk::mfree(job); + } +} + +static int browse_worker(void* arg) { + BrowseJob* job = (BrowseJob*)arg; + smb::MontaukLink link; + int r = smb::link_open(&link, job->host, job->port); + if (r == smb::OK) { + smb::Client client; + smb::Credentials creds = {job->user, job->password, job->domain}; + r = smb::connect(&client, smb::link_io(&link), job->host, creds); + if (r == smb::OK) { + auto* shares = (smb::ShareInfo*)montauk::malloc(sizeof(smb::ShareInfo) * BROWSE_MAX); + if (shares == nullptr) { + r = smb::ERR_NOMEM; + } else { + r = smb::list_shares(&client, shares, BROWSE_MAX); + int kept = 0; + for (int i = 0; i < r; i++) { + // Folders people can open: disk shares that are not administrative. + if (shares[i].type != smb::SHARE_TYPE_DISK || shares[i].hidden) continue; + montauk::strncpy(job->names[kept], shares[i].name, sizeof(job->names[kept])); + montauk::strncpy(job->comments[kept], shares[i].comment, sizeof(job->comments[kept])); + kept++; + } + if (r >= 0) r = kept; + montauk::mfree(shares); + } + } + smb::disconnect(&client); + smb::link_close(&link); + } + job->count = r; + __atomic_store_n(&job->done, 1, __ATOMIC_RELEASE); + browse_release(job); + return 0; +} + +// ============================================================================ +// Connect to Server dialog +// ============================================================================ + +enum ConnectField : int { + CF_SERVER = 0, + CF_SHARE, + CF_USER, + CF_PASSWORD, + CF_COUNT, +}; + +struct ConnectDialogState { + DesktopState* desktop; + FileManagerState* owner; + Color accent; + int mouse_x; + int mouse_y; + + char text[CF_COUNT][128]; + mtk::TextInputState input[CF_COUNT]; + int focus; + bool remember; + int port; + + // Share list filled by Browse. + BrowseJob* browse; + char share_names[BROWSE_MAX][96]; + char share_comments[BROWSE_MAX][64]; + int share_count; + int share_scroll; + bool browsed; + + // Mount in progress. + bool connecting; + smb::MountJob job; + NetShare pending; + + char status[160]; + bool status_error; +}; + +static constexpr int CD_W = 440; +static constexpr int CD_PAD = 16; +static constexpr int CD_BTN_H = 30; +static constexpr int CD_FIELD_H = 30; +static constexpr int CD_ROW_H = 24; +static constexpr int CD_LIST_ROWS = 5; +static constexpr int CD_BROWSE_W = 96; + +static const char* const CD_LABELS[CF_COUNT] = {"Server", "Share", "User name", "Password"}; + +struct ConnectLayout { + int label_y[CF_COUNT]; + Rect field[CF_COUNT]; + Rect browse; + Rect remember; + Rect list; + int status_y; + Rect connect; + Rect cancel; +}; + +static ConnectLayout cd_layout(int cw, int ch, const mtk::Theme& theme) { + ConnectLayout lo; + int fh = system_font_height(); + int w = cw - CD_PAD * 2; + int y = CD_PAD; + for (int i = 0; i < CF_COUNT; i++) { + int fw = i == CF_SHARE ? w - CD_BROWSE_W - 8 : w; + lo.label_y[i] = y; + lo.field[i] = mtk::labeled_text_input_rect(CD_PAD, y, fw, theme, CD_FIELD_H); + y = lo.field[i].y + CD_FIELD_H + 10; + } + lo.browse = {CD_PAD + w - CD_BROWSE_W, lo.field[CF_SHARE].y, CD_BROWSE_W, CD_FIELD_H}; + lo.remember = {CD_PAD, y, w, 22}; + y += 22 + 10; + lo.list = {CD_PAD, y + fh + 4, w, CD_ROW_H * CD_LIST_ROWS}; + lo.status_y = lo.list.y + lo.list.h + 10; + int btn_w = 96; + int btn_h = CD_BTN_H; + int by = ch - CD_PAD - btn_h; + lo.cancel = {cw - CD_PAD - btn_w, by, btn_w, btn_h}; + lo.connect = {lo.cancel.x - 8 - btn_w, by, btn_w, btn_h}; + return lo; +} + +// Window height that fits the top-down layout (fields, list, status line) +// above the bottom-anchored buttons. The fields' height follows the font, so +// a fixed height let the list run into the buttons. +static int cd_window_height(const mtk::Theme& theme) { + ConnectLayout lo = cd_layout(CD_W, 0, theme); + int content_h = lo.status_y + system_font_height() + 12 + CD_BTN_H + CD_PAD; + return content_h + gui::TITLEBAR_HEIGHT + gui::BORDER_WIDTH; +} + +static void cd_set_status(ConnectDialogState* st, const char* text, bool error) { + montauk::strncpy(st->status, text ? text : "", sizeof(st->status)); + st->status_error = error; +} + +static void cd_set_field(ConnectDialogState* st, int field, const char* text) { + montauk::strncpy(st->text[field], text ? text : "", sizeof(st->text[field])); + mtk::text_input_reset(st->input[field], montauk::slen(st->text[field])); +} + +static void cd_close(ConnectDialogState* st) { + DesktopState* ds = st->desktop; + for (int i = 0; ds && i < ds->window_count; i++) { + if (ds->windows[i].app_data == st) { + desktop_close_window(ds, i); + return; + } + } +} + +// The Files window that opened the dialog, if it is still there. +static FileManagerState* cd_live_owner(ConnectDialogState* st) { + DesktopState* ds = st->desktop; + for (int i = 0; ds && i < ds->window_count; i++) { + Window& w = ds->windows[i]; + if (w.app_data == st->owner && w.on_draw == filemanager_on_draw) return st->owner; + } + return nullptr; +} + +// Accept "DOMAIN\user" and "user@domain" in the user name field. +static void cd_split_user(const char* text, char* user, int user_max, char* domain, int domain_max) { + user[0] = '\0'; + domain[0] = '\0'; + const char* sep = nullptr; + for (const char* p = text; *p; p++) { + if (*p == '\\' || *p == '/') { sep = p; break; } + } + if (sep) { + int n = (int)(sep - text); + if (n >= domain_max) n = domain_max - 1; + montauk::memcpy(domain, text, n); + domain[n] = '\0'; + montauk::strncpy(user, sep + 1, user_max); + return; + } + montauk::strncpy(user, text, user_max); +} + +static void cd_trim(char* s) { + int len = montauk::slen(s); + while (len > 0 && s[len - 1] == ' ') s[--len] = '\0'; + int lead = 0; + while (s[lead] == ' ') lead++; + if (lead > 0) { + for (int i = 0; i <= len - lead; i++) s[i] = s[i + lead]; + } +} + +// Read the form into a NetShare. The server field may also hold a whole +// "smb://host/share" or "\\host\share" address. +static bool cd_read_form(ConnectDialogState* st, NetShare* out, bool need_share) { + montauk::memset(out, 0, sizeof(*out)); + char server[128]; + montauk::strncpy(server, st->text[CF_SERVER], sizeof(server)); + cd_trim(server); + + smb::Url url; + if (!smb::parse_url(server, &url)) { + cd_set_status(st, "Enter the name or address of the server.", true); + st->focus = CF_SERVER; + return false; + } + montauk::strncpy(out->host, url.host, sizeof(out->host)); + out->port = url.port ? url.port : st->port; + + char share[128]; + montauk::strncpy(share, st->text[CF_SHARE], sizeof(share)); + cd_trim(share); + if (!share[0]) montauk::strncpy(share, url.share, sizeof(share)); + montauk::strncpy(out->share, share, sizeof(out->share)); + if (need_share && !out->share[0]) { + cd_set_status(st, "Enter the share to open, or press Browse to list them.", true); + st->focus = CF_SHARE; + return false; + } + + char user[128]; + montauk::strncpy(user, st->text[CF_USER], sizeof(user)); + cd_trim(user); + if (!user[0] && url.user[0]) { + montauk::strncpy(out->user, url.user, sizeof(out->user)); + montauk::strncpy(out->domain, url.domain, sizeof(out->domain)); + } else { + cd_split_user(user, out->user, sizeof(out->user), out->domain, sizeof(out->domain)); + } + montauk::strncpy(out->password, st->text[CF_PASSWORD], sizeof(out->password)); + + if (!smb::mount_arg_ok(out->host) || !smb::mount_arg_ok(out->share) || + !smb::mount_arg_ok(out->user) || !smb::mount_arg_ok(out->domain)) { + cd_set_status(st, "Names may not contain quotation marks.", true); + return false; + } + return true; +} + +static void cd_start_browse(ConnectDialogState* st) { + if (st->browse || st->connecting) return; + NetShare form; + if (!cd_read_form(st, &form, false)) return; + + auto* job = (BrowseJob*)montauk::malloc(sizeof(BrowseJob)); + if (!job) return; + montauk::memset(job, 0, sizeof(*job)); + job->refs = 2; + montauk::strncpy(job->host, form.host, sizeof(job->host)); + montauk::strncpy(job->user, form.user, sizeof(job->user)); + montauk::strncpy(job->domain, form.domain, sizeof(job->domain)); + montauk::strncpy(job->password, form.password, sizeof(job->password)); + job->port = form.port; + + int tid = montauk::thread_spawn(browse_worker, job, 256 * 1024); + if (tid <= 0) { + montauk::mfree(job); + cd_set_status(st, "Couldn't start looking for shares.", true); + return; + } + job->tid = tid; + st->browse = job; + st->share_count = 0; + st->share_scroll = 0; + cd_set_status(st, "Looking for shares...", false); +} + +static void cd_start_connect(ConnectDialogState* st) { + if (st->connecting) return; + NetShare form; + if (!cd_read_form(st, &form, true)) return; + + DesktopState* ds = st->desktop; + FileManagerState* owner = cd_live_owner(st); + int mounted = smb::find_mount(form.host, form.share); + if (mounted >= 0) { + char path[16]; + snprintf(path, sizeof(path), "%d:/", mounted); + cd_close(st); + if (owner) filemanager_go_to_path(owner, path); + (void)ds; + return; + } + + smb::MountRequest rq; + rq.host = form.host; + rq.share = form.share; + rq.user = form.user; + rq.domain = form.domain; + rq.password = form.password; + rq.label = ""; + rq.port = form.port; + rq.readOnly = false; + if (!smb::mount_begin(&st->job, rq)) { + cd_set_status(st, "Couldn't start the network share helper.", true); + return; + } + st->pending = form; + st->connecting = true; + cd_set_status(st, "Connecting...", false); +} + +static void cd_connect_finished(ConnectDialogState* st, int drive) { + DesktopState* ds = st->desktop; + FileManagerState* owner = cd_live_owner(st); + + NetShare saved = st->pending; + saved.has_password = st->remember && saved.user[0] != '\0'; + if (!saved.has_password) montauk::memset(saved.password, 0, sizeof(saved.password)); + net_remember(ds, saved); + + char path[16]; + snprintf(path, sizeof(path), "%d:/", drive); + cd_close(st); // frees st + if (owner) { + filemanager_sidebar_rebuild(owner); + filemanager_go_to_path(owner, path); + } +} + +static void cd_on_poll(Window* win) { + ConnectDialogState* st = (ConnectDialogState*)win->app_data; + if (!st) return; + + if (st->browse && __atomic_load_n(&st->browse->done, __ATOMIC_ACQUIRE)) { + BrowseJob* job = st->browse; + st->browse = nullptr; + montauk::thread_join(job->tid, nullptr); + st->browsed = true; + st->share_count = 0; + if (job->count < 0) { + char msg[160]; + snprintf(msg, sizeof(msg), "Couldn't list the shares: %s.", + job->count == smb::ERR_NOT_FOUND ? "server not found" + : job->count == smb::ERR_IO ? "could not connect to the server" + : smb::status_text(job->count)); + cd_set_status(st, msg, true); + if (job->count == smb::ERR_AUTH) st->focus = CF_USER; + } else { + for (int i = 0; i < job->count && i < BROWSE_MAX; i++) { + montauk::strncpy(st->share_names[i], job->names[i], sizeof(st->share_names[i])); + montauk::strncpy(st->share_comments[i], job->comments[i], sizeof(st->share_comments[i])); + } + st->share_count = job->count; + cd_set_status(st, job->count ? "Choose a share, then press Connect." + : "The server offers no shares to this account.", false); + } + browse_release(job); + win->dirty = true; + } + + if (st->connecting) { + int drive = -1; + int status = 0; + char error[160]; + int r = smb::mount_poll(&st->job, &drive, &status, error, sizeof(error)); + if (r > 0) { + cd_connect_finished(st, drive); + return; // the dialog is gone + } + if (r < 0) { + st->connecting = false; + char msg[200]; + snprintf(msg, sizeof(msg), "Couldn't connect: %s.", error); + cd_set_status(st, msg, true); + if (status == smb::ERR_AUTH || status == smb::ERR_ACCESS) { + st->focus = st->text[CF_USER][0] ? CF_PASSWORD : CF_USER; + int len = montauk::slen(st->text[st->focus]); + st->input[st->focus].selection_anchor = 0; + st->input[st->focus].cursor = len; + } else if (status == smb::ERR_BAD_SHARE) { + st->focus = CF_SHARE; + } + win->dirty = true; + } + } +} + +static void cd_on_draw(Window* win, Framebuffer& fb) { + (void)fb; + ConnectDialogState* st = (ConnectDialogState*)win->app_data; + if (!st) return; + + Canvas c(win); + mtk::Theme theme = mtk::make_theme(st->accent); + c.fill(theme.window_bg); + ConnectLayout lo = cd_layout(c.w, c.h, theme); + int fh = system_font_height(); + bool busy = st->connecting; + + for (int i = 0; i < CF_COUNT; i++) { + mtk::draw_labeled_text_field(c, lo.field[i].x, lo.label_y[i], lo.field[i].w, CD_LABELS[i], + st->text[i], st->input[i].cursor, st->focus == i && !busy, + i == CF_PASSWORD, theme, CD_FIELD_H, + st->input[i].selection_anchor); + } + if (!st->text[CF_USER][0] && st->focus != CF_USER) { + c.text(lo.field[CF_USER].x + 8, lo.field[CF_USER].y + (CD_FIELD_H - fh) / 2, + "Leave empty to connect as a guest", theme.text_subtle); + } + + bool can_browse = !busy && !st->browse; + mtk::draw_button(c, lo.browse, st->browse ? "Looking..." : "Browse", mtk::BUTTON_SECONDARY, + mtk::widget_state(false, can_browse && lo.browse.contains(st->mouse_x, st->mouse_y), + can_browse), + theme); + + mtk::draw_checkbox(c, lo.remember, "Remember password", mtk::check_state(st->remember), theme, + !busy, lo.remember.contains(st->mouse_x, st->mouse_y)); + + // Share list. + c.text(lo.list.x, lo.list.y - fh - 4, "Shares on the server", theme.text_muted); + c.fill_rect(lo.list.x, lo.list.y, lo.list.w, lo.list.h, colors::WHITE); + c.rect(lo.list.x - 1, lo.list.y - 1, lo.list.w + 2, lo.list.h + 2, theme.border); + if (st->share_count == 0) { + c.text(lo.list.x + 10, lo.list.y + 8, + st->browsed ? "No shares to show." : "Press Browse to list the shares.", + theme.text_muted); + } + for (int v = 0; v < CD_LIST_ROWS; v++) { + int i = st->share_scroll + v; + if (i >= st->share_count) break; + Rect r = {lo.list.x + 1, lo.list.y + v * CD_ROW_H, lo.list.w - 2, CD_ROW_H}; + bool selected = montauk::streq(st->share_names[i], st->text[CF_SHARE]); + if (selected) c.fill_rect(r.x, r.y, r.w, r.h, gui::mtk::accent_hover_tint(st->accent)); + else if (r.contains(st->mouse_x, st->mouse_y)) c.fill_rect(r.x, r.y, r.w, r.h, theme.surface_alt); + const SvgIcon* icon = filemanager_net_drive_icon(false); + if (icon) c.icon(r.x + 6, r.y + (CD_ROW_H - icon->height) / 2, *icon); + char fit[96]; + filemanager_fit_text(st->share_names[i], fit, sizeof(fit), 150); + c.text(r.x + 28, r.y + (CD_ROW_H - fh) / 2, fit, theme.text); + filemanager_fit_text(st->share_comments[i], fit, sizeof(fit), r.w - 200); + c.text(r.x + 190, r.y + (CD_ROW_H - fh) / 2, fit, theme.text_muted); + } + if (st->share_count > CD_LIST_ROWS) { + int thumb_h = lo.list.h * CD_LIST_ROWS / st->share_count; + if (thumb_h < 16) thumb_h = 16; + int max_scroll = st->share_count - CD_LIST_ROWS; + int thumb_y = lo.list.y + (lo.list.h - thumb_h) * st->share_scroll / max_scroll; + c.fill_rect(lo.list.x + lo.list.w - 6, thumb_y, 4, thumb_h, theme.border); + } + + if (st->status[0]) { + char fit[160]; + filemanager_fit_text(st->status, fit, sizeof(fit), c.w - CD_PAD * 2); + c.text(CD_PAD, lo.status_y, fit, st->status_error ? theme.danger : theme.text_muted); + } + + mtk::draw_button(c, lo.connect, busy ? "Connecting..." : "Connect", mtk::BUTTON_PRIMARY, + mtk::widget_state(false, !busy && lo.connect.contains(st->mouse_x, st->mouse_y), + !busy), + theme); + mtk::draw_button(c, lo.cancel, "Cancel", mtk::BUTTON_SECONDARY, + mtk::widget_state(false, lo.cancel.contains(st->mouse_x, st->mouse_y), true), + theme); + + for (int i = 0; i < CF_COUNT; i++) { + if (!st->input[i].context.open) continue; + mtk::draw_text_input_context_menu( + c, st->input[i], theme, + mtk::text_input_has_selection(st->input[i], st->text[i], sizeof(st->text[i])), + i == CF_PASSWORD); + } +} + +static void cd_on_mouse(Window* win, MouseEvent& ev) { + ConnectDialogState* st = (ConnectDialogState*)win->app_data; + if (!st) return; + + mtk::DesktopHost host(win); + int mx = 0; + int my = 0; + if (!host.map_mouse(ev, &mx, &my)) return; + if (mx != st->mouse_x || my != st->mouse_y) host.invalidate(); + st->mouse_x = mx; + st->mouse_y = my; + + mtk::Theme theme = mtk::make_theme(st->accent); + ConnectLayout lo = cd_layout(win->content_w, win->content_h, theme); + + if (lo.cancel.contains(mx, my) && ev.left_pressed()) { + cd_close(st); + return; + } + if (st->connecting) return; + + // An open field menu takes every event. + for (int i = 0; i < CF_COUNT; i++) { + if (!st->input[i].context.open) continue; + mtk::text_input_handle_mouse(st->input[i], lo.field[i], st->text[i], sizeof(st->text[i]), + mx, my, ev.buttons, ev.prev_buttons, win->content_w, + win->content_h, true, i == CF_PASSWORD); + host.invalidate(); + return; + } + + for (int i = 0; i < CF_COUNT; i++) { + bool inside = lo.field[i].contains(mx, my); + if ((ev.left_pressed() || ev.right_pressed()) && inside) st->focus = i; + if (st->focus != i) continue; + int result = mtk::text_input_handle_mouse(st->input[i], lo.field[i], st->text[i], + sizeof(st->text[i]), mx, my, ev.buttons, + ev.prev_buttons, win->content_w, win->content_h, + true, i == CF_PASSWORD); + if (result != mtk::TEXT_INPUT_NONE) host.invalidate(); + } + + if (ev.scroll != 0 && lo.list.contains(mx, my)) { + int max_scroll = st->share_count - CD_LIST_ROWS; + st->share_scroll -= ev.scroll; + if (st->share_scroll > max_scroll) st->share_scroll = max_scroll; + if (st->share_scroll < 0) st->share_scroll = 0; + host.invalidate(); + } + + if (!ev.left_pressed()) return; + host.invalidate(); + + if (lo.browse.contains(mx, my)) { + cd_start_browse(st); + } else if (lo.remember.contains(mx, my)) { + st->remember = !st->remember; + } else if (lo.list.contains(mx, my)) { + int i = st->share_scroll + (my - lo.list.y) / CD_ROW_H; + if (i >= 0 && i < st->share_count) cd_set_field(st, CF_SHARE, st->share_names[i]); + } else if (lo.connect.contains(mx, my)) { + cd_start_connect(st); + } +} + +static void cd_on_key(Window* win, const montauk::abi::KeyEvent& key) { + ConnectDialogState* st = (ConnectDialogState*)win->app_data; + if (!st || !key.pressed) return; + + if (key.scancode == 0x01) { // Escape + cd_close(st); + return; + } + if (st->connecting) return; + + if (key.ascii == '\n' || key.ascii == '\r') { + cd_start_connect(st); + return; + } + if (key.ascii == '\t') { + st->focus = (st->focus + (key.shift ? CF_COUNT - 1 : 1)) % CF_COUNT; + int len = montauk::slen(st->text[st->focus]); + st->input[st->focus].selection_anchor = 0; + st->input[st->focus].cursor = len; + return; + } + mtk::text_input_key(st->input[st->focus], st->text[st->focus], sizeof(st->text[st->focus]), + key, nullptr, nullptr, st->focus == CF_PASSWORD); + if (st->status_error) cd_set_status(st, "", false); +} + +static void cd_on_close(Window* win) { + ConnectDialogState* st = (ConnectDialogState*)win->app_data; + if (!st) return; + + if (st->connecting) smb::mount_cancel(&st->job); + // A browse still running finishes on its own and frees the job. + if (st->browse) browse_release(st->browse); + + FileManagerState* owner = cd_live_owner(st); + if (owner && owner->connect_dialog == st) owner->connect_dialog = nullptr; + + montauk::memset(st, 0, sizeof(*st)); // drops the typed password + montauk::mfree(st); + win->app_data = nullptr; +} + +// Open the dialog, prefilled from saved share `saved_index` (-1 = empty). +// A saved share that needs no more input starts connecting right away. +void filemanager_net_show_connect(FileManagerState* fm, int saved_index) { + if (!fm || !fm->desktop) return; + DesktopState* ds = fm->desktop; + + if (fm->connect_dialog) { + for (int i = 0; i < ds->window_count; i++) { + if (ds->windows[i].app_data == fm->connect_dialog) { + desktop_raise_window(ds, i); + return; + } + } + fm->connect_dialog = nullptr; + } + + auto* st = (ConnectDialogState*)montauk::malloc(sizeof(ConnectDialogState)); + if (!st) return; + montauk::memset(st, 0, sizeof(*st)); + st->desktop = ds; + st->owner = fm; + st->accent = ds->settings.accent_color; + st->job.pid = -1; + for (int i = 0; i < CF_COUNT; i++) mtk::text_input_reset(st->input[i], 0); + + bool ready = false; + if (saved_index >= 0 && saved_index < g_share_count) { + const NetShare& s = g_shares[saved_index]; + cd_set_field(st, CF_SERVER, s.host); + cd_set_field(st, CF_SHARE, s.share); + char user[160]; + if (s.domain[0]) snprintf(user, sizeof(user), "%s\\%s", s.domain, s.user); + else snprintf(user, sizeof(user), "%s", s.user); + cd_set_field(st, CF_USER, user); + st->port = s.port; + if (s.has_password) { + cd_set_field(st, CF_PASSWORD, s.password); + st->remember = true; + } + // Guests and remembered passwords need nothing typed. + ready = !s.user[0] || s.has_password; + st->focus = ready ? CF_SERVER : CF_PASSWORD; + } + + int wx = 0; + int wy = 0; + int cd_h = cd_window_height(mtk::make_theme(st->accent)); + props_center_dialog(ds, fm, CD_W, cd_h, &wx, &wy); + int idx = desktop_create_window(ds, "Connect to Server", wx, wy, CD_W, cd_h); + if (idx < 0) { + montauk::mfree(st); + return; + } + + Window* win = &ds->windows[idx]; + fm->connect_dialog = st; + win->app_data = st; + win->on_draw = cd_on_draw; + win->on_mouse = cd_on_mouse; + win->on_key = cd_on_key; + win->on_poll = cd_on_poll; + win->on_close = cd_on_close; + + if (ready) cd_start_connect(st); +} + +// A saved share was chosen in the sidebar: open it if it is mounted, +// otherwise connect to it. +void filemanager_net_open_saved(FileManagerState* fm, int saved_index) { + if (saved_index < 0 || saved_index >= g_share_count) return; + int drive = smb::find_mount(g_shares[saved_index].host, g_shares[saved_index].share); + if (drive >= 0) { + char path[16]; + snprintf(path, sizeof(path), "%d:/", drive); + filemanager_go_to_path(fm, path); + return; + } + filemanager_net_show_connect(fm, saved_index); +} + +} // namespace filemanager diff --git a/programs/src/files/render.cpp b/programs/src/files/render.cpp index 010d0d7..bb80078 100644 --- a/programs/src/files/render.cpp +++ b/programs/src/files/render.cpp @@ -428,8 +428,11 @@ void filemanager_on_draw(Window* win, Framebuffer& fb) { c.icon(icon_x, icon_y, (fm->drive_indices[i] && ds->icon_trash_full_lg.pixels) ? ds->icon_trash_full_lg : ds->icon_trash_lg); } else if (ds && fm->entry_types[i] == FM_ENTRY_DRIVE && ds->icon_drive_lg.pixels) { - // Kind 4 = USB MSC (kernel BlockDeviceKind enum) - const SvgIcon& di = (fm->drive_kinds[i] == 4 && ds->icon_drive_usb_lg.pixels) + // Kind 4 = USB MSC (kernel BlockDeviceKind enum), 6 = network share + const SvgIcon* net = fm->drive_kinds[i] == FM_DRIVE_KIND_NETWORK + ? filemanager_net_drive_icon(true) : nullptr; + const SvgIcon& di = net ? *net + : (fm->drive_kinds[i] == 4 && ds->icon_drive_usb_lg.pixels) ? ds->icon_drive_usb_lg : ds->icon_drive_lg; c.icon(icon_x, icon_y, di); } else if (ds && fm->entry_types[i] == FM_ENTRY_DIR && ds->icon_folder_lg.pixels) { @@ -574,7 +577,10 @@ void filemanager_on_draw(Window* win, Framebuffer& fb) { c.icon(ico_x, ico_y, (fm->drive_indices[i] && ds->icon_trash_full.pixels) ? ds->icon_trash_full : ds->icon_trash); } else if (ds && fm->entry_types[i] == FM_ENTRY_DRIVE && ds->icon_drive.pixels) { - const SvgIcon& di = (fm->drive_kinds[i] == 4 && ds->icon_drive_usb.pixels) + const SvgIcon* net = fm->drive_kinds[i] == FM_DRIVE_KIND_NETWORK + ? filemanager_net_drive_icon(false) : nullptr; + const SvgIcon& di = net ? *net + : (fm->drive_kinds[i] == 4 && ds->icon_drive_usb.pixels) ? ds->icon_drive_usb : ds->icon_drive; c.icon(ico_x, ico_y, di); } else if (ds && fm->entry_types[i] == FM_ENTRY_DIR && ds->icon_folder.pixels) { diff --git a/programs/src/files/sidebar.cpp b/programs/src/files/sidebar.cpp index e1c27cc..093bb76 100644 --- a/programs/src/files/sidebar.cpp +++ b/programs/src/files/sidebar.cpp @@ -68,10 +68,16 @@ void filemanager_sidebar_rebuild(FileManagerState* fm) { } } + // Local drives, then (below) the network ones. int drives[FM_MAX_DRIVES]; + int kinds[FM_MAX_DRIVES]; int drive_count = montauk::drivelist(drives, FM_MAX_DRIVES); - if (drive_count > 0) sidebar_add(fm, FM_SIDEBAR_HEADER, "Drives", nullptr); + int local_count = 0; for (int i = 0; i < drive_count; i++) { + kinds[i] = montauk::drivekind(drives[i]); + if (kinds[i] != FM_DRIVE_KIND_NETWORK) local_count++; + } + auto add_drive = [&](int i) { int d = drives[i]; char path[8]; snprintf(path, sizeof(path), "%d:/", d); @@ -82,9 +88,32 @@ void filemanager_sidebar_rebuild(FileManagerState* fm) { else snprintf(label, sizeof(label), "Volume %d", d); FileManagerSidebarItem* item = sidebar_add(fm, FM_SIDEBAR_DRIVE, label, path); - if (item) item->drive_kind = montauk::drivekind(d); + if (item) { + item->drive_kind = kinds[i]; + item->drive = d; + } + }; + if (local_count > 0) sidebar_add(fm, FM_SIDEBAR_HEADER, "Drives", nullptr); + for (int i = 0; i < drive_count; i++) { + if (kinds[i] != FM_DRIVE_KIND_NETWORK) add_drive(i); } + // Network: mounted shares, saved shares that are not mounted, and the + // way to reach a new one. + filemanager_net_load(ds); + sidebar_add(fm, FM_SIDEBAR_HEADER, "Network", nullptr); + for (int i = 0; i < drive_count; i++) { + if (kinds[i] == FM_DRIVE_KIND_NETWORK) add_drive(i); + } + for (int i = 0; i < filemanager_net_share_count(); i++) { + char label[64]; + int mounted = -1; + if (!filemanager_net_share(i, label, sizeof(label), &mounted) || mounted >= 0) continue; + FileManagerSidebarItem* item = sidebar_add(fm, FM_SIDEBAR_NETSHARE, label, nullptr); + if (item) item->net_index = i; + } + sidebar_add(fm, FM_SIDEBAR_CONNECT, "Connect to Server...", nullptr); + if (fm->sidebar_hover >= fm->sidebar_count) fm->sidebar_hover = -1; } @@ -121,7 +150,13 @@ static const SvgIcon* sidebar_icon(FileManagerState* fm, const FileManagerSideba return filemanager_trash_has_items(ds) && ds->icon_trash_full.pixels ? &ds->icon_trash_full : &ds->icon_trash; case FM_SIDEBAR_DRIVE: + if (item.drive_kind == FM_DRIVE_KIND_NETWORK && filemanager_net_drive_icon(false)) + return filemanager_net_drive_icon(false); return item.drive_kind == 4 && ds->icon_drive_usb.pixels ? &ds->icon_drive_usb : &ds->icon_drive; + case FM_SIDEBAR_NETSHARE: + return filemanager_net_drive_icon(false) ? filemanager_net_drive_icon(false) : &ds->icon_drive; + case FM_SIDEBAR_CONNECT: + return filemanager_net_connect_icon(); case FM_SIDEBAR_FOLDER: if (item.special_index >= 0) return &ds->icon_special_folder[item.special_index]; if (!item.bookmark && ds->home_dir[0] && same_path(item.path, ds->home_dir)) @@ -184,7 +219,9 @@ void filemanager_sidebar_draw(Canvas& c, FileManagerState* fm, const FileManager if (icon && icon->pixels) c.icon(12, y + (FM_SIDEBAR_ITEM_H - icon->height) / 2, *icon); char fit[64]; filemanager_fit_text(item.label, fit, sizeof(fit), l.sidebar_w - 40); - c.text(34, y + (FM_SIDEBAR_ITEM_H - fh) / 2, fit, colors::TEXT_COLOR); + // A saved share that is not connected reads as inactive. + c.text(34, y + (FM_SIDEBAR_ITEM_H - fh) / 2, fit, + item.kind == FM_SIDEBAR_NETSHARE ? muted : colors::TEXT_COLOR); } } @@ -201,6 +238,8 @@ void filemanager_sidebar_open(FileManagerState* fm, int idx) { switch (item.kind) { case FM_SIDEBAR_COMPUTER: filemanager_go_home(fm); break; case FM_SIDEBAR_TRASH: filemanager_open_trash(fm); break; + case FM_SIDEBAR_NETSHARE: filemanager_net_open_saved(fm, item.net_index); break; + case FM_SIDEBAR_CONNECT: filemanager_net_show_connect(fm, -1); break; case FM_SIDEBAR_FOLDER: case FM_SIDEBAR_DRIVE: { char path[256]; diff --git a/programs/src/smb/Makefile b/programs/src/smb/Makefile new file mode 100644 index 0000000..f6151f6 --- /dev/null +++ b/programs/src/smb/Makefile @@ -0,0 +1,64 @@ +# Makefile for smb (SMB share command-line tool) on MontaukOS +# Copyright (c) 2026 Daniel Hammer + +MAKEFLAGS += -rR +.SUFFIXES: + +include ../../mk/arch.mk +ifeq ($(wildcard $(TOOLCHAIN_PREFIX)gcc),) + CXX = $(error $(TOOLCHAIN_MISSING)) +else + CXX := $(TOOLCHAIN_PREFIX)g++ +endif + +PROG_INC := ../../include +LIBC_LIB := ../../lib/libc +SMB_LIB := ../../lib/smb +BEARSSL := ../../lib/bearssl +LINK_LD := ../../link.ld +BINDIR := ../../bin$(ARCH_SUFFIX) +OBJDIR := obj$(ARCH_SUFFIX) +CXXFLAGS := \ + -std=gnu++20 \ + -g -O2 -pipe \ + -Wall \ + -Wextra \ + -Wno-unused-parameter \ + -ffreestanding \ + -fno-stack-protector \ + -fno-stack-check \ + -fno-rtti \ + -fno-exceptions \ + -ffunction-sections \ + -fdata-sections \ + $(ARCH_NOFP_FLAGS) \ + -I $(PROG_INC) \ + -isystem $(PROG_INC)/libc + +LDFLAGS := \ + -nostdlib \ + -Wl,--gc-sections \ + -T $(LINK_LD) + +SRCS := main.cpp +OBJS := $(addprefix $(OBJDIR)/,$(SRCS:.cpp=.o)) +LIBS := $(SMB_LIB)/$(ARCH_OUT)libsmb.a $(BEARSSL)/build$(ARCH_SUFFIX)/libbearssl.a $(LIBC_LIB)/$(ARCH_OUT)liblibc.a +TARGET := $(BINDIR)/os/smb.elf +DEPS := $(OBJS:.o=.d) + +.PHONY: all clean + +all: $(TARGET) + +$(TARGET): $(OBJS) $(LIBS) $(LINK_LD) Makefile + mkdir -p $(BINDIR)/os + $(CXX) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + +$(OBJDIR)/%.o: %.cpp Makefile + mkdir -p $(OBJDIR) + $(CXX) $(CXXFLAGS) -MMD -MP -c $< -o $@ + +-include $(DEPS) + +clean: + rm -rf $(OBJDIR) $(TARGET) diff --git a/programs/src/smb/main.cpp b/programs/src/smb/main.cpp new file mode 100644 index 0000000..7feebdc --- /dev/null +++ b/programs/src/smb/main.cpp @@ -0,0 +1,259 @@ +/* + * main.cpp + * smb - list, mount and unmount SMB shares from the command line + * Copyright (c) 2026 Daniel Hammer +*/ + +#include +#include +#include +#include + +#include +#include +#include +#include + +static void out(const char* fmt, ...) { + char line[512]; + va_list ap; + va_start(ap, fmt); + vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + montauk::print(line); +} + +static void usage() { + montauk::print( + "Usage: smb [options]\n" + " smb shares //host List the shares a server offers\n" + " smb mount //host/share Mount a share as a drive\n" + " smb list Show mounted shares\n" + " smb unmount Disconnect a mounted share\n" + "Options for shares and mount:\n" + " --user NAME Log on as NAME (default: guest)\n" + " --domain NAME Domain or workgroup of the account\n" + " --password PW Password (otherwise SMB_PASSWORD, or you are asked)\n" + " --port N Server port (default 445)\n" + " --label TEXT Drive label (mount)\n" + " --ro Mount read-only (mount)\n"); +} + +// Split the argument string on spaces, honouring double quotes. +static int split_args(char* buf, char** argv, int max) { + int argc = 0; + char* p = buf; + while (*p && argc < max) { + while (*p == ' ') p++; + if (!*p) break; + char* o = p; + argv[argc++] = o; + bool quoted = false; + while (*p && (quoted || *p != ' ')) { + if (*p == '"') quoted = !quoted; + else *o++ = *p; + p++; + } + if (*p) p++; + *o = '\0'; + } + return argc; +} + +// Read a line from the terminal without echoing it. +static void read_password(const char* prompt, char* buf, int cap) { + montauk::print(prompt); + int len = 0; + for (;;) { + montauk::abi::KeyEvent ev; + montauk::getkey(&ev); + if (!ev.pressed) continue; + if (ev.ascii == '\n' || ev.ascii == '\r') break; + if (ev.ascii == '\b' || ev.ascii == 0x7F) { + if (len > 0) len--; + continue; + } + if ((unsigned char)ev.ascii >= 0x20 && len < cap - 1) buf[len++] = ev.ascii; + } + buf[len] = '\0'; + montauk::print("\n"); +} + +struct Options { + const char* target = nullptr; + const char* user = ""; + const char* domain = ""; + const char* label = ""; + const char* password = nullptr; + int port = 0; + bool readOnly = false; +}; + +static char g_password[256]; + +// Settle on a password: --password, then SMB_PASSWORD, then a prompt (only +// when a user name was given; a guest logon has none). +static const char* resolve_password(const Options& o, const char* user) { + if (o.password) return o.password; + const char* env = getenv("SMB_PASSWORD"); + if (env) return env; + if (user[0] == '\0') return ""; + char prompt[200]; + snprintf(prompt, sizeof(prompt), "Password for %s: ", user); + read_password(prompt, g_password, sizeof(g_password)); + return g_password; +} + +static int cmd_shares(const Options& o) { + smb::Url url; + if (o.target == nullptr || !smb::parse_url(o.target, &url)) { usage(); return 2; } + const char* user = o.user[0] ? o.user : url.user; + const char* domain = o.domain[0] ? o.domain : url.domain; + const char* password = resolve_password(o, user); + + smb::MontaukLink link; + int r = smb::link_open(&link, url.host, o.port ? o.port : url.port); + if (r != smb::OK) { + out("smb: %s: %s\n", url.host, r == smb::ERR_NOT_FOUND ? "server not found" : "could not connect"); + return 1; + } + smb::Client client; + smb::Credentials creds = {user, password, domain}; + r = smb::connect(&client, smb::link_io(&link), url.host, creds); + if (r != smb::OK) { + out("smb: %s: %s\n", url.host, smb::status_text(r)); + smb::disconnect(&client); + smb::link_close(&link); + return 1; + } + + static smb::ShareInfo shares[128]; + int n = smb::list_shares(&client, shares, 128); + if (n < 0) { + out("smb: could not list shares: %s\n", smb::status_text(n)); + } else { + out("Shares on %s (SMB %x.%x%s):\n", url.host, client.dialect >> 8, (client.dialect >> 4) & 0xF, + client.guest ? ", guest" : ""); + for (int i = 0; i < n; i++) { + const char* kind = shares[i].type == smb::SHARE_TYPE_DISK ? "disk" + : shares[i].type == smb::SHARE_TYPE_PRINTER ? "printer" + : shares[i].type == smb::SHARE_TYPE_IPC ? "ipc" : "device"; + out(" %-24s %-8s %s\n", shares[i].name, kind, shares[i].comment); + } + } + smb::disconnect(&client); + smb::link_close(&link); + return n < 0 ? 1 : 0; +} + +static int cmd_mount(const Options& o) { + smb::Url url; + if (o.target == nullptr || !smb::parse_url(o.target, &url) || url.share[0] == '\0') { usage(); return 2; } + const char* user = o.user[0] ? o.user : url.user; + + int existing = smb::find_mount(url.host, url.share); + if (existing >= 0) { + out("smb: //%s/%s is already mounted as %d:/\n", url.host, url.share, existing); + return 0; + } + + smb::MountRequest rq; + rq.host = url.host; + rq.share = url.share; + rq.user = user; + rq.domain = o.domain[0] ? o.domain : url.domain; + rq.password = resolve_password(o, user); + rq.label = o.label; + rq.port = o.port ? o.port : url.port; + rq.readOnly = o.readOnly; + + smb::MountJob job; + if (!smb::mount_begin(&job, rq)) { + montauk::print("smb: could not start 0:/os/smbfs.elf\n"); + return 1; + } + for (;;) { + int drive = -1, status = 0; + char error[160]; + int r = smb::mount_poll(&job, &drive, &status, error, sizeof(error)); + if (r > 0) { + out("Mounted //%s/%s as %d:/\n", url.host, url.share, drive); + return 0; + } + if (r < 0) { + out("smb: mount failed: %s\n", error); + return 1; + } + montauk::sleep_ms(50); + } +} + +static int cmd_list() { + int drives[64]; + int n = montauk::drivelist(drives, 64); + int shown = 0; + for (int i = 0; i < n; i++) { + montauk::abi::UserFsInfo info; + if (montauk::userfs_info(drives[i], &info) != 0) continue; + out("%2d:/ %-28s %s%s\n", info.drive, info.source, info.label, + (info.flags & montauk::abi::USERFS_MOUNT_READONLY) ? " (read-only)" : ""); + shown++; + } + if (shown == 0) montauk::print("No shares are mounted.\n"); + return 0; +} + +static int cmd_unmount(const Options& o) { + if (o.target == nullptr) { usage(); return 2; } + int drive = atoi(o.target); + montauk::abi::UserFsInfo info; + if (montauk::userfs_info(drive, &info) != 0) { + out("smb: drive %d is not a mounted share\n", drive); + return 1; + } + if (smb::unmount(drive) != 0) { + out("smb: not allowed to unmount drive %d\n", drive); + return 1; + } + // The provider flushes and exits; wait for the drive to go. + for (int i = 0; i < 100; i++) { + if (montauk::userfs_info(drive, &info) != 0) { + out("Unmounted %d:/\n", drive); + return 0; + } + montauk::sleep_ms(50); + } + out("smb: drive %d is still busy\n", drive); + return 1; +} + +extern "C" void _start() { + static char args[1024]; + montauk::getargs(args, sizeof(args)); + char* argv[32]; + int argc = split_args(args, argv, 32); + if (argc < 1) { usage(); montauk::exit(2); } + + Options o; + for (int i = 1; i < argc; i++) { + const char* a = argv[i]; + const char* next = i + 1 < argc ? argv[i + 1] : nullptr; + if (!strcmp(a, "--user") && next) { o.user = next; i++; } + else if (!strcmp(a, "--domain") && next) { o.domain = next; i++; } + else if (!strcmp(a, "--label") && next) { o.label = next; i++; } + else if (!strcmp(a, "--password") && next) { o.password = next; i++; } + else if (!strcmp(a, "--port") && next) { o.port = atoi(next); i++; } + else if (!strcmp(a, "--ro")) o.readOnly = true; + else if (a[0] != '-' || (a[0] == '-' && a[1] == '\0')) o.target = a; + else { usage(); montauk::exit(2); } + } + + int rc; + if (!strcmp(argv[0], "shares")) rc = cmd_shares(o); + else if (!strcmp(argv[0], "mount")) rc = cmd_mount(o); + else if (!strcmp(argv[0], "list")) rc = cmd_list(); + else if (!strcmp(argv[0], "unmount") || !strcmp(argv[0], "umount")) rc = cmd_unmount(o); + else { usage(); rc = 2; } + memset(g_password, 0, sizeof(g_password)); + montauk::exit(rc); +} diff --git a/programs/src/smbfs/Makefile b/programs/src/smbfs/Makefile new file mode 100644 index 0000000..2e84ece --- /dev/null +++ b/programs/src/smbfs/Makefile @@ -0,0 +1,64 @@ +# Makefile for smbfs (SMB share mount daemon) on MontaukOS +# Copyright (c) 2026 Daniel Hammer + +MAKEFLAGS += -rR +.SUFFIXES: + +include ../../mk/arch.mk +ifeq ($(wildcard $(TOOLCHAIN_PREFIX)gcc),) + CXX = $(error $(TOOLCHAIN_MISSING)) +else + CXX := $(TOOLCHAIN_PREFIX)g++ +endif + +PROG_INC := ../../include +LIBC_LIB := ../../lib/libc +SMB_LIB := ../../lib/smb +BEARSSL := ../../lib/bearssl +LINK_LD := ../../link.ld +BINDIR := ../../bin$(ARCH_SUFFIX) +OBJDIR := obj$(ARCH_SUFFIX) +CXXFLAGS := \ + -std=gnu++20 \ + -g -O2 -pipe \ + -Wall \ + -Wextra \ + -Wno-unused-parameter \ + -ffreestanding \ + -fno-stack-protector \ + -fno-stack-check \ + -fno-rtti \ + -fno-exceptions \ + -ffunction-sections \ + -fdata-sections \ + $(ARCH_NOFP_FLAGS) \ + -I $(PROG_INC) \ + -isystem $(PROG_INC)/libc + +LDFLAGS := \ + -nostdlib \ + -Wl,--gc-sections \ + -T $(LINK_LD) + +SRCS := main.cpp +OBJS := $(addprefix $(OBJDIR)/,$(SRCS:.cpp=.o)) +LIBS := $(SMB_LIB)/$(ARCH_OUT)libsmb.a $(BEARSSL)/build$(ARCH_SUFFIX)/libbearssl.a $(LIBC_LIB)/$(ARCH_OUT)liblibc.a +TARGET := $(BINDIR)/os/smbfs.elf +DEPS := $(OBJS:.o=.d) + +.PHONY: all clean + +all: $(TARGET) + +$(TARGET): $(OBJS) $(LIBS) $(LINK_LD) Makefile + mkdir -p $(BINDIR)/os + $(CXX) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + +$(OBJDIR)/%.o: %.cpp Makefile + mkdir -p $(OBJDIR) + $(CXX) $(CXXFLAGS) -MMD -MP -c $< -o $@ + +-include $(DEPS) + +clean: + rm -rf $(OBJDIR) $(TARGET) diff --git a/programs/src/smbfs/main.cpp b/programs/src/smbfs/main.cpp new file mode 100644 index 0000000..a0606fc --- /dev/null +++ b/programs/src/smbfs/main.cpp @@ -0,0 +1,679 @@ +/* + * main.cpp + * smbfs - mounts an SMB share as a MontaukOS drive + * Copyright (c) 2026 Daniel Hammer +*/ + +// smbfs is a userspace filesystem provider (see Api/Syscall.hpp, SYS_USERFS_*): +// it logs on to an SMB server, registers a drive with the kernel and then +// serves every file operation other programs perform on that drive by talking +// SMB2 to the server. The share stays mounted for as long as this process +// lives; ejecting the drive (Files, `smb unmount`) asks it to exit. +// +// smbfs //host/share [--user NAME] [--domain DOMAIN] [--port N] +// [--label TEXT] [--ro] +// +// The password is taken from the SMB_PASSWORD environment variable so it never +// appears in an argument list. On startup exactly one status line is written +// to standard output, for the program that launched it: +// +// OK mounted as :/ +// ERR could not mount (status is an smb::Status) + +#include +#include +#include +#include + +#include +#include +#include +#include + +using montauk::abi::UserFsRequest; +using montauk::abi::FileStat; + +// Kernel status codes (negative on the wire) used in replies. +static constexpr int64_t ST_GENERIC = -1; +static constexpr int64_t ST_PERMISSION = -2; +static constexpr int64_t ST_INVALID = -6; +static constexpr int64_t ST_UNSUPPORTED = -7; +static constexpr int64_t ST_IO = -9; +static constexpr int64_t ST_NO_PATH = -11; +static constexpr int64_t ST_BUSY = -12; +static constexpr int64_t ST_NO_MEMORY = -14; +static constexpr int64_t ST_TIMED_OUT = -15; +static constexpr int64_t ST_EXISTS = -18; + +// ============================================================================ +// State +// ============================================================================ + +static constexpr int MAX_HANDLES = 256; +// Listings kept so that paging through a directory and the stat() calls that +// follow a listing do not each cost server round trips. +static constexpr int DIR_CACHE_SLOTS = 4; +static constexpr uint64_t DIR_CACHE_TTL_MS = 5000; +// Send a keepalive after this long without any request. +static constexpr uint64_t IDLE_ECHO_MS = 30000; +// After a failed reconnect, fail requests fast for this long instead of +// making each one wait for another connection attempt. +static constexpr uint64_t RECONNECT_HOLDOFF_MS = 5000; + +struct Handle { + bool used; + bool live; // `id` is valid on the current session + bool writable; + bool dirty; // written to since it was opened + uint32_t generation; // session generation `id` belongs to + uint64_t size; + smb::FileId id; + char path[256]; +}; + +struct CachedEntry { + char* name; + smb::FileInfo info; +}; + +struct DirCache { + bool valid; + uint64_t stamp; // when it was fetched + uint64_t lastUse; + char path[256]; + CachedEntry* entries; + int count; + int cap; +}; + +static smb::MontaukLink g_link = {-1}; +static smb::Client g_client; +static bool g_clientInit = false; +static uint32_t g_tree = 0; +static uint32_t g_generation = 0; +static uint64_t g_lastFailedConnect = 0; +static bool g_everConnected = false; + +static char g_host[256]; +static char g_share[256]; +static char g_user[128]; +static char g_domain[128]; +static char g_password[256]; +static char g_label[36]; +static int g_port = 0; +static bool g_readOnly = false; +static int g_drive = -1; + +static Handle g_handles[MAX_HANDLES]; +static DirCache g_dirs[DIR_CACHE_SLOTS]; +static uint8_t g_data[montauk::abi::USERFS_MAX_DATA]; +static uint8_t g_reply[montauk::abi::USERFS_MAX_DATA]; + +static void log_msg(const char* fmt, ...) { + char line[320]; + int n = snprintf(line, sizeof(line), "smbfs[%s/%s]: ", g_host, g_share); + va_list ap; + va_start(ap, fmt); + vsnprintf(line + n, sizeof(line) - (size_t)n, fmt, ap); + va_end(ap); + montauk::write_log(line); +} + +// ============================================================================ +// Connection +// ============================================================================ + +static void drop_connection() { + if (g_clientInit) { + // The link may be dead; do not attempt a logoff over it. + g_client.connected = false; + smb::disconnect(&g_client); + g_clientInit = false; + } + smb::link_close(&g_link); + for (int i = 0; i < MAX_HANDLES; i++) g_handles[i].live = false; +} + +// Connect, log on and attach to the share. Returns an smb::Status. +static int establish() { + drop_connection(); + int r = smb::link_open(&g_link, g_host, g_port); + if (r != smb::OK) return r; + + smb::Credentials creds = {g_user, g_password, g_domain}; + g_clientInit = true; + r = smb::connect(&g_client, smb::link_io(&g_link), g_host, creds); + if (r == smb::OK) r = smb::tree_connect(&g_client, g_share, &g_tree); + if (r != smb::OK) { + drop_connection(); + return r; + } + g_generation++; + return smb::OK; +} + +static bool connection_lost(int status) { + return status == smb::ERR_IO || status == smb::ERR_TIMEOUT || !g_client.connected; +} + +// Make sure there is a live session, reconnecting if the last one died. +static bool ensure_connected() { + if (g_clientInit && g_client.connected) return true; + uint64_t now = montauk::get_milliseconds(); + if (g_lastFailedConnect != 0 && now - g_lastFailedConnect < RECONNECT_HOLDOFF_MS) return false; + int r = establish(); + if (r != smb::OK) { + g_lastFailedConnect = montauk::get_milliseconds(); + log_msg("reconnect failed: %s", smb::status_text(r)); + return false; + } + g_lastFailedConnect = 0; + log_msg("reconnected"); + return true; +} + +// Run an operation, reconnecting and retrying once if the link dropped. +template +static int with_retry(Op op) { + if (!ensure_connected()) return smb::ERR_IO; + int r = op(); + if (r < 0 && connection_lost(r)) { + drop_connection(); + if (!ensure_connected()) return smb::ERR_IO; + r = op(); + } + return r; +} + +static int64_t to_status(int smbStatus) { + switch (smbStatus) { + case smb::ERR_NOT_FOUND: return ST_NO_PATH; + case smb::ERR_ACCESS: + case smb::ERR_AUTH: + case smb::ERR_READ_ONLY: return ST_PERMISSION; + case smb::ERR_EXISTS: return ST_EXISTS; + case smb::ERR_BUSY: + case smb::ERR_NOT_EMPTY: return ST_BUSY; + case smb::ERR_INVALID: + case smb::ERR_IS_DIR: + case smb::ERR_NOT_DIR: return ST_INVALID; + case smb::ERR_UNSUPPORTED: return ST_UNSUPPORTED; + case smb::ERR_NOMEM: return ST_NO_MEMORY; + case smb::ERR_TIMEOUT: return ST_TIMED_OUT; + case smb::ERR_IO: + case smb::ERR_NO_SPACE: return ST_IO; + default: return ST_GENERIC; + } +} + +// ============================================================================ +// Directory cache +// ============================================================================ + +static void dir_free(DirCache* d) { + for (int i = 0; i < d->count; i++) free(d->entries[i].name); + free(d->entries); + d->entries = nullptr; + d->count = 0; + d->cap = 0; + d->valid = false; +} + +static void invalidate_dirs() { + for (int i = 0; i < DIR_CACHE_SLOTS; i++) dir_free(&g_dirs[i]); +} + +static bool dir_collect(void* ctx, const smb::DirEntry& e) { + DirCache* d = (DirCache*)ctx; + if (d->count == d->cap) { + int cap = d->cap ? d->cap * 2 : 64; + CachedEntry* grown = (CachedEntry*)realloc(d->entries, (size_t)cap * sizeof(CachedEntry)); + if (grown == nullptr) return false; + d->entries = grown; + d->cap = cap; + } + size_t len = strlen(e.name); + char* name = (char*)malloc(len + 1); + if (name == nullptr) return false; + memcpy(name, e.name, len + 1); + d->entries[d->count].name = name; + d->entries[d->count].info = e.info; + d->count++; + return true; +} + +// Listing of `path`, from the cache if it is fresh enough (or `anyAge`). +static DirCache* dir_get(const char* path, bool anyAge, int* status) { + uint64_t now = montauk::get_milliseconds(); + DirCache* slot = nullptr; + for (int i = 0; i < DIR_CACHE_SLOTS; i++) { + DirCache* d = &g_dirs[i]; + if (d->valid && !strcmp(d->path, path)) { + if (anyAge || now - d->stamp < DIR_CACHE_TTL_MS) { + d->lastUse = now; + return d; + } + slot = d; + break; + } + } + if (slot == nullptr) { + slot = &g_dirs[0]; + for (int i = 0; i < DIR_CACHE_SLOTS; i++) { + if (!g_dirs[i].valid) { slot = &g_dirs[i]; break; } + if (g_dirs[i].lastUse < slot->lastUse) slot = &g_dirs[i]; + } + } + + dir_free(slot); + int r = with_retry([&] { + dir_free(slot); + return smb::list_dir(&g_client, g_tree, path, dir_collect, slot); + }); + if (r < 0) { + dir_free(slot); + *status = r; + return nullptr; + } + slot->valid = true; + slot->stamp = montauk::get_milliseconds(); + slot->lastUse = slot->stamp; + snprintf(slot->path, sizeof(slot->path), "%s", path); + return slot; +} + +// Look `path` up in a fresh cached listing of its parent directory. +static bool stat_from_cache(const char* path, smb::FileInfo* out) { + const char* slash = strrchr(path, '/'); + if (slash == nullptr || slash[1] == '\0') return false; + char parent[256]; + size_t plen = (size_t)(slash - path); + if (plen == 0) plen = 1; // parent is the root + if (plen >= sizeof(parent)) return false; + memcpy(parent, path, plen); + parent[plen] = '\0'; + + uint64_t now = montauk::get_milliseconds(); + for (int i = 0; i < DIR_CACHE_SLOTS; i++) { + DirCache* d = &g_dirs[i]; + if (!d->valid || strcmp(d->path, parent) != 0 || now - d->stamp >= DIR_CACHE_TTL_MS) continue; + for (int k = 0; k < d->count; k++) { + if (!strcmp(d->entries[k].name, slash + 1)) { + *out = d->entries[k].info; + return true; + } + } + // A fresh listing without the name: let the server give the verdict + // (the name may differ only in case). + return false; + } + return false; +} + +// ============================================================================ +// Request handlers +// ============================================================================ + +static Handle* handle_for(int index) { + if (index < 0 || index >= MAX_HANDLES || !g_handles[index].used) return nullptr; + return &g_handles[index]; +} + +// (Re)open a handle's file on the current session if needed. +static int handle_revive(Handle* h) { + if (h->live && h->generation == g_generation) return smb::OK; + smb::FileInfo info; + int r = smb::ERR_ACCESS; + if (h->writable) r = smb::open(&g_client, g_tree, h->path, smb::OPEN_READWRITE, &h->id, &info); + if (r != smb::OK && !connection_lost(r)) { + r = smb::open(&g_client, g_tree, h->path, smb::OPEN_READ, &h->id, &info); + if (r == smb::OK) h->writable = false; + } + if (r != smb::OK) return r; + h->live = true; + h->generation = g_generation; + return smb::OK; +} + +static int64_t op_open(const UserFsRequest& req, bool create) { + int index = -1; + for (int i = 0; i < MAX_HANDLES; i++) { + if (!g_handles[i].used) { index = i; break; } + } + if (index < 0) return ST_BUSY; + Handle* h = &g_handles[index]; + memset(h, 0, sizeof(*h)); + snprintf(h->path, sizeof(h->path), "%s", req.path); + + smb::FileInfo info; + memset(&info, 0, sizeof(info)); + int r = with_retry([&] { + if (create) { + h->writable = true; + return smb::open(&g_client, g_tree, h->path, smb::OPEN_CREATE, &h->id, &info); + } + int rr = smb::ERR_ACCESS; + if (!g_readOnly) { + rr = smb::open(&g_client, g_tree, h->path, smb::OPEN_READWRITE, &h->id, &info); + if (rr == smb::OK) h->writable = true; + } + // Read-only files, shares and sharing conflicts still allow reading. + if (rr == smb::ERR_ACCESS || rr == smb::ERR_READ_ONLY || rr == smb::ERR_BUSY) { + rr = smb::open(&g_client, g_tree, h->path, smb::OPEN_READ, &h->id, &info); + if (rr == smb::OK) h->writable = false; + } + return rr; + }); + if (r != smb::OK) return to_status(r); + + h->used = true; + h->live = true; + h->generation = g_generation; + h->size = info.size; + if (create) invalidate_dirs(); + return index; +} + +static void op_close(const UserFsRequest& req) { + Handle* h = handle_for(req.handle); + if (h == nullptr) return; + if (h->live && h->generation == g_generation && g_clientInit && g_client.connected) { + smb::close(&g_client, g_tree, h->id); + } + if (h->dirty) invalidate_dirs(); + h->used = false; +} + +static int64_t op_read(const UserFsRequest& req, uint32_t* replyLen) { + Handle* h = handle_for(req.handle); + if (h == nullptr) return ST_INVALID; + uint32_t want = req.size > req.replyMax ? req.replyMax : (uint32_t)req.size; + if (want > sizeof(g_reply)) want = sizeof(g_reply); + + uint32_t done = 0; + int r = with_retry([&] { + int rr = handle_revive(h); + if (rr != smb::OK) return rr; + while (done < want) { + int n = smb::read(&g_client, g_tree, h->id, req.offset + done, g_reply + done, want - done); + if (n < 0) return n; + if (n == 0) break; + done += (uint32_t)n; + } + return (int)smb::OK; + }); + if (r != smb::OK && done == 0) return to_status(r); + *replyLen = done; + return done; +} + +static int64_t op_write(const UserFsRequest& req) { + Handle* h = handle_for(req.handle); + if (h == nullptr) return ST_INVALID; + if (!h->writable || g_readOnly) return ST_PERMISSION; + uint32_t want = req.dataLen; + + uint32_t done = 0; + int r = with_retry([&] { + int rr = handle_revive(h); + if (rr != smb::OK) return rr; + if (!h->writable) return (int)smb::ERR_ACCESS; + while (done < want) { + int n = smb::write(&g_client, g_tree, h->id, req.offset + done, g_data + done, want - done); + if (n < 0) return n; + if (n == 0) break; + done += (uint32_t)n; + } + return (int)smb::OK; + }); + if (done > 0) { + h->dirty = true; + if (req.offset + done > h->size) h->size = req.offset + done; + } + if (r != smb::OK && done == 0) return to_status(r); + return done; +} + +static int64_t op_readdir(const UserFsRequest& req, uint32_t* replyLen) { + int status = smb::OK; + // Later pages must come from the listing the first page came from. + DirCache* d = dir_get(req.path, req.offset > 0, &status); + if (d == nullptr) return to_status(status); + + uint32_t cap = req.replyMax < sizeof(g_reply) ? req.replyMax : (uint32_t)sizeof(g_reply); + uint32_t pos = 0; + int count = 0; + for (uint64_t i = req.offset; i < (uint64_t)d->count && (uint64_t)count < req.size; i++) { + const CachedEntry& e = d->entries[i]; + size_t len = strlen(e.name); + size_t need = len + (e.info.isDir ? 1 : 0) + 1; + if (pos + need > cap) break; + memcpy(g_reply + pos, e.name, len); + pos += (uint32_t)len; + if (e.info.isDir) g_reply[pos++] = '/'; + g_reply[pos++] = '\0'; + count++; + } + *replyLen = pos; + return count; +} + +static int64_t op_stat(const UserFsRequest& req, uint32_t* replyLen) { + smb::FileInfo info; + memset(&info, 0, sizeof(info)); + if (!stat_from_cache(req.path, &info)) { + int r = with_retry([&] { return smb::stat(&g_client, g_tree, req.path, &info); }); + if (r != smb::OK) return to_status(r); + } + + FileStat st; + memset(&st, 0, sizeof(st)); + st.size = info.size; + st.mtime = info.mtime; + st.ctime = info.ctime; + st.atime = info.atime; + st.isDir = info.isDir ? 1u : 0u; + bool readOnly = g_readOnly || (info.attributes & smb::ATTR_READONLY) != 0; + st.mode = info.isDir ? (0x4000u | (readOnly ? 0555u : 0755u)) + : (0x8000u | (readOnly ? 0444u : 0644u)); + memcpy(g_reply, &st, sizeof(st)); + *replyLen = sizeof(st); + return 0; +} + +static int64_t op_mutate(const UserFsRequest& req) { + if (g_readOnly) return ST_PERMISSION; + int r = with_retry([&] { + switch (req.op) { + case montauk::abi::USERFS_OP_DELETE: + return smb::remove(&g_client, g_tree, req.path); + case montauk::abi::USERFS_OP_MKDIR: + return smb::mkdir(&g_client, g_tree, req.path); + case montauk::abi::USERFS_OP_RENAME: + return smb::rename(&g_client, g_tree, req.path, req.path2, false); + case montauk::abi::USERFS_OP_SETTIMES: + return smb::set_times(&g_client, g_tree, req.path, req.atime, req.mtime); + } + return (int)smb::ERR_INVALID; + }); + invalidate_dirs(); + if (r == smb::OK && req.op == montauk::abi::USERFS_OP_RENAME) { + // Open handles follow the file on the server, but a later reopen + // (after a reconnect) must use the new name. + size_t oldLen = strlen(req.path); + for (int i = 0; i < MAX_HANDLES; i++) { + Handle* h = &g_handles[i]; + if (!h->used || strncmp(h->path, req.path, oldLen) != 0) continue; + if (h->path[oldLen] != '\0' && h->path[oldLen] != '/') continue; + char moved[256]; + snprintf(moved, sizeof(moved), "%s%s", req.path2, h->path + oldLen); + memcpy(h->path, moved, sizeof(moved)); + } + } + return r == smb::OK ? 0 : to_status(r); +} + +// Drop trailing separators so "/dir/" and "/dir" name the same cache entry. +static void normalize_path(char* path) { + size_t len = strlen(path); + while (len > 1 && path[len - 1] == '/') path[--len] = '\0'; +} + +[[noreturn]] static void shut_down(int code) { + for (int i = 0; i < MAX_HANDLES; i++) { + Handle* h = &g_handles[i]; + if (h->used && h->live && h->generation == g_generation && g_clientInit && g_client.connected) + smb::close(&g_client, g_tree, h->id); + } + if (g_drive >= 0) montauk::userfs_unmount(g_drive); + if (g_clientInit) { + if (g_client.connected) smb::tree_disconnect(&g_client, g_tree); + smb::disconnect(&g_client); + } + smb::link_close(&g_link); + memset(g_password, 0, sizeof(g_password)); + montauk::exit(code); +} + +static void serve() { + UserFsRequest req; + for (;;) { + int got = montauk::userfs_recv(g_drive, &req, g_data, sizeof(g_data), IDLE_ECHO_MS); + if (got < 0) { + log_msg("drive lost, exiting"); + shut_down(1); + } + if (got == 0) { + // Idle: keep the session alive and notice a dead link early. + if (g_clientInit && g_client.connected && smb::echo(&g_client) != smb::OK) drop_connection(); + continue; + } + + normalize_path(req.path); + normalize_path(req.path2); + + uint32_t replyLen = 0; + int64_t result = ST_UNSUPPORTED; + switch (req.op) { + case montauk::abi::USERFS_OP_OPEN: result = op_open(req, false); break; + case montauk::abi::USERFS_OP_CREATE: + result = g_readOnly ? ST_PERMISSION : op_open(req, true); + break; + case montauk::abi::USERFS_OP_CLOSE: op_close(req); break; + case montauk::abi::USERFS_OP_READ: result = op_read(req, &replyLen); break; + case montauk::abi::USERFS_OP_WRITE: result = op_write(req); break; + case montauk::abi::USERFS_OP_GETSIZE: { + Handle* h = handle_for(req.handle); + result = h ? (int64_t)h->size : ST_INVALID; + break; + } + case montauk::abi::USERFS_OP_READDIR: result = op_readdir(req, &replyLen); break; + case montauk::abi::USERFS_OP_STAT: result = op_stat(req, &replyLen); break; + case montauk::abi::USERFS_OP_DELETE: + case montauk::abi::USERFS_OP_MKDIR: + case montauk::abi::USERFS_OP_RENAME: + case montauk::abi::USERFS_OP_SETTIMES: result = op_mutate(req); break; + case montauk::abi::USERFS_OP_UNMOUNT: + log_msg("ejected"); + shut_down(0); + } + if (req.id != 0) montauk::userfs_reply(g_drive, req.id, result, g_reply, replyLen); + } +} + +// ============================================================================ +// Startup +// ============================================================================ + +[[noreturn]] static void fail(int status, const char* message) { + char line[256]; + snprintf(line, sizeof(line), "ERR %d %s\n", status, message); + montauk::print(line); + log_msg("mount failed: %s", message); + shut_down(1); +} + +// Split the argument string on spaces, honouring double quotes. +static int split_args(char* buf, char** argv, int max) { + int argc = 0; + char* p = buf; + while (*p && argc < max) { + while (*p == ' ') p++; + if (!*p) break; + char* out = p; + argv[argc++] = out; + bool quoted = false; + while (*p && (quoted || *p != ' ')) { + if (*p == '"') quoted = !quoted; + else *out++ = *p; + p++; + } + if (*p) p++; + *out = '\0'; + } + return argc; +} + +extern "C" void _start() { + static char args[1024]; + montauk::getargs(args, sizeof(args)); + char* argv[32]; + int argc = split_args(args, argv, 32); + + const char* target = nullptr; + for (int i = 0; i < argc; i++) { + const char* a = argv[i]; + const char* next = i + 1 < argc ? argv[i + 1] : nullptr; + if (!strcmp(a, "--user") && next) { snprintf(g_user, sizeof(g_user), "%s", next); i++; } + else if (!strcmp(a, "--domain") && next) { snprintf(g_domain, sizeof(g_domain), "%s", next); i++; } + else if (!strcmp(a, "--label") && next) { snprintf(g_label, sizeof(g_label), "%s", next); i++; } + else if (!strcmp(a, "--port") && next) { g_port = atoi(next); i++; } + else if (!strcmp(a, "--ro")) g_readOnly = true; + else if (a[0] != '-') target = a; + } + + smb::Url url; + if (target == nullptr || !smb::parse_url(target, &url) || url.share[0] == '\0') { + montauk::print("ERR -16 usage: smbfs //host/share [--user NAME] [--domain DOMAIN] " + "[--port N] [--label TEXT] [--ro]\n"); + montauk::exit(2); + } + snprintf(g_host, sizeof(g_host), "%s", url.host); + snprintf(g_share, sizeof(g_share), "%s", url.share); + if (g_user[0] == '\0') snprintf(g_user, sizeof(g_user), "%s", url.user); + if (g_domain[0] == '\0') snprintf(g_domain, sizeof(g_domain), "%s", url.domain); + if (g_port == 0) g_port = url.port; + if (g_label[0] == '\0') snprintf(g_label, sizeof(g_label), "%.20s on %.10s", g_share, g_host); + + const char* password = getenv("SMB_PASSWORD"); + if (password != nullptr) { + snprintf(g_password, sizeof(g_password), "%s", password); + unsetenv("SMB_PASSWORD"); // keep it out of anything this process spawns + } + + int r = establish(); + if (r != smb::OK) { + if (r == smb::ERR_NOT_FOUND) fail(r, "server not found"); + if (r == smb::ERR_IO) fail(r, "could not connect to the server"); + fail(r, smb::status_text(r)); + } + g_everConnected = true; + + montauk::abi::UserFsMountParams params; + memset(¶ms, 0, sizeof(params)); + snprintf(params.label, sizeof(params.label), "%s", g_label); + snprintf(params.fsType, sizeof(params.fsType), "smb"); + snprintf(params.source, sizeof(params.source), "smb://%s/%s", g_host, g_share); + params.flags = g_readOnly ? montauk::abi::USERFS_MOUNT_READONLY : 0; + g_drive = montauk::userfs_mount(¶ms); + if (g_drive < 0) fail(smb::ERR_FAILED, "no free drive for the share"); + + char line[64]; + snprintf(line, sizeof(line), "OK %d\n", g_drive); + montauk::print(line); + log_msg("mounted as %d:/ (SMB %x.%x%s%s)", g_drive, g_client.dialect >> 8, + (g_client.dialect >> 4) & 0xF, g_client.signing ? ", signed" : "", + g_client.guest ? ", guest" : ""); + + serve(); +} diff --git a/scripts/copy_icons.sh b/scripts/copy_icons.sh index ac0e715..9325d76 100755 --- a/scripts/copy_icons.sh +++ b/scripts/copy_icons.sh @@ -131,6 +131,8 @@ ICONS=( "apps/symbolic/utilities-system-monitor-symbolic.svg" # system monitor "apps/scalable/utilities-system-monitor.svg" # system monitor "apps/scalable/drive-harddisk.svg" + "apps/scalable/network-server.svg" # Files: network share + "apps/scalable/network-workgroup.svg" # Files: Connect to Server "actions/16/trash-empty.svg" "places/scalable/folder-blue-home.svg" "places/scalable/folder-blue-development.svg" diff --git a/tests/smb/kshim/Arch/Cpu.hpp b/tests/smb/kshim/Arch/Cpu.hpp new file mode 100644 index 0000000..4526c03 --- /dev/null +++ b/tests/smb/kshim/Arch/Cpu.hpp @@ -0,0 +1,3 @@ +#pragma once +#include +namespace Arch { inline void Pause() { sched_yield(); } } diff --git a/tests/smb/kshim/Arch/Syscall.hpp b/tests/smb/kshim/Arch/Syscall.hpp new file mode 100644 index 0000000..82b86b6 --- /dev/null +++ b/tests/smb/kshim/Arch/Syscall.hpp @@ -0,0 +1,2 @@ +#pragma once +namespace Arch { struct SyscallFrame; } diff --git a/tests/smb/kshim/CppLib/Spinlock.hpp b/tests/smb/kshim/CppLib/Spinlock.hpp new file mode 100644 index 0000000..1b1281d --- /dev/null +++ b/tests/smb/kshim/CppLib/Spinlock.hpp @@ -0,0 +1,13 @@ +#pragma once +#include +#include +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; +} diff --git a/tests/smb/kshim/Libraries/Memory.hpp b/tests/smb/kshim/Libraries/Memory.hpp new file mode 100644 index 0000000..80b2a09 --- /dev/null +++ b/tests/smb/kshim/Libraries/Memory.hpp @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/tests/smb/kshim/Libraries/String.hpp b/tests/smb/kshim/Libraries/String.hpp new file mode 100644 index 0000000..80b2a09 --- /dev/null +++ b/tests/smb/kshim/Libraries/String.hpp @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/tests/smb/kshim/Sched/Scheduler.hpp b/tests/smb/kshim/Sched/Scheduler.hpp new file mode 100644 index 0000000..6f7fef1 --- /dev/null +++ b/tests/smb/kshim/Sched/Scheduler.hpp @@ -0,0 +1,19 @@ +#pragma once +// Host stand-in for the kernel scheduler: every pthread is a "process". +#include +#include +namespace Sched { + struct Process { + int pid = -1; + int sessionId = 0; + std::atomic 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); +} diff --git a/tests/smb/kshim/Terminal/Terminal.hpp b/tests/smb/kshim/Terminal/Terminal.hpp new file mode 100644 index 0000000..9600fe3 --- /dev/null +++ b/tests/smb/kshim/Terminal/Terminal.hpp @@ -0,0 +1,9 @@ +#pragma once +#include +namespace Kt { + enum KernelLogLevel { INFO, OK, WARNING, ERROR }; + struct KernelLogStream { + KernelLogStream(KernelLogLevel, const char*) {} + template KernelLogStream& operator<<(const T&) { return *this; } + }; +} diff --git a/tests/smb/kshim/Timekeeping/Timer.hpp b/tests/smb/kshim/Timekeeping/Timer.hpp new file mode 100644 index 0000000..2f8c66e --- /dev/null +++ b/tests/smb/kshim/Timekeeping/Timer.hpp @@ -0,0 +1,3 @@ +#pragma once +#include +namespace Timekeeping { uint64_t GetMilliseconds(); } diff --git a/tests/smb/mount_harness.cpp b/tests/smb/mount_harness.cpp new file mode 100644 index 0000000..2b8678b --- /dev/null +++ b/tests/smb/mount_harness.cpp @@ -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 +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 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* tl_vanish = nullptr; + +static std::mutex g_wakeLock; +static std::condition_variable g_wakeCv; +static uint64_t g_wakeEpoch = 1; +static std::atomic 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 lk(g_wakeLock); + return g_wakeEpoch; + } + + bool BlockOnObjectSince(void*, uint64_t timeoutMs, uint64_t observed) { + { + std::unique_lock 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 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(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 paused{false}; + std::atomic stop{false}; + std::atomic served{0}; + std::atomic closes{0}; + std::atomic ejects{0}; + std::atomic badWrites{0}; + std::thread thread; + + void start() { + std::atomic 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 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(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 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 okCount{0}; + std::vector 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 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 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 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 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 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 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 g_providerExited{false}; +static std::atomic 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 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 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 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 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 okCount{0}; + std::vector ts; + for (int t = 0; t < 6; t++) { + ts.emplace_back([&, t] { + become(700 + t); + Vfs::BackendFile tf; + std::vector 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 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 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; +} diff --git a/tests/smb/run.sh b/tests/smb/run.sh new file mode 100755 index 0000000..bdafc62 --- /dev/null +++ b/tests/smb/run.sh @@ -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" </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 diff --git a/tests/smb/server.py b/tests/smb/server.py new file mode 100644 index 0000000..0d79115 --- /dev/null +++ b/tests/smb/server.py @@ -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() diff --git a/tests/smb/smb_test.cpp b/tests/smb/smb_test.cpp new file mode 100644 index 0000000..0e86650 --- /dev/null +++ b/tests/smb/smb_test.cpp @@ -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 +#include "../../programs/lib/smb/internal.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +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 unhex(const char* s) { + std::vector 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;alice@nas.local: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 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 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 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; +} diff --git a/tests/smb/ushim/montauk/syscall.h b/tests/smb/ushim/montauk/syscall.h new file mode 100644 index 0000000..918f6cd --- /dev/null +++ b/tests/smb/ushim/montauk/syscall.h @@ -0,0 +1,94 @@ +// Host stand-in for , for running smbfs and the SMB +// library's MontaukOS transport inside tests/smb/mount_harness. +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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; + } +}