feat: add SMB networking support

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

No files matched your search

+73 -1
View File
@@ -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];
+5
View File
@@ -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++). */
+27
View File
@@ -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);
}
+23
View File
@@ -0,0 +1,23 @@
/*
* montauk.hpp
* MontaukOS transport for the SMB client library
* Copyright (c) 2026 Daniel Hammer
*/
#pragma once
#include <smb/smb.hpp>
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);
}
+158
View File
@@ -0,0 +1,158 @@
/*
* mount.hpp
* Launching and managing smbfs mounts from other programs
* Copyright (c) 2026 Daniel Hammer
*/
#pragma once
#include <montauk/syscall.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 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);
}
}
+213
View File
@@ -0,0 +1,213 @@
/*
* smb.hpp
* SMB2/SMB3 client library
* Copyright (c) 2026 Daniel Hammer
*/
#pragma once
#include <stdint.h>
#include <stddef.h>
// 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, <string.h> 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);
}