feat: add SMB networking support
This commit is contained in:
1 parent
6665750528
commit
2af2e90606
55 files changed
+7456
-158
No files matched your search
@@ -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);
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user