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

+18 -4
View File
@@ -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/<name>/.
@@ -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
+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);
}
+71
View File
@@ -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)
+174
View File
@@ -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 <bearssl_hash.h>
#include <bearssl_hmac.h>
#include <bearssl_block.h>
}
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);
}
}
+88
View File
@@ -0,0 +1,88 @@
/*
* internal.hpp
* SMB client library internals: byte order, crypto, NTLM, SPNEGO
* Copyright (c) 2026 Daniel Hammer
*/
#pragma once
#include <smb/smb.hpp>
#include <string.h>
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);
}
+111
View File
@@ -0,0 +1,111 @@
/*
* montauk_io.cpp
* MontaukOS transport for the SMB client library
* Copyright (c) 2026 Daniel Hammer
*/
#include <smb/montauk.hpp>
#include <montauk/syscall.h>
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;
}
}
+283
View File
@@ -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;
}
}
File diff suppressed because it is too large. Load diff
+61
View File
@@ -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)
+39
View File
@@ -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)
+1 -1
View File
@@ -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
+8
View File
@@ -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)
+6
View File
@@ -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) {
+46 -2
View File
@@ -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 <home>/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.
+198 -24
View File
@@ -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);
+60 -4
View File
@@ -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;
}
+6 -1
View File
@@ -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:
+961
View File
@@ -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 <gui/mtk/hosts.hpp>
#include <montauk/config.h>
#include <montauk/thread.h>
#include <smb/smb.hpp>
#include <smb/montauk.hpp>
#include <smb/mount.hpp>
// 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 <home>/config/network.toml:
// [shares]
// list = ["host|share|user|domain|port|<password hex>|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
+9 -3
View File
@@ -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) {
+42 -3
View File
@@ -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];
+64
View File
@@ -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)
+259
View File
@@ -0,0 +1,259 @@
/*
* main.cpp
* smb - list, mount and unmount SMB shares from the command line
* Copyright (c) 2026 Daniel Hammer
*/
#include <montauk/syscall.h>
#include <smb/smb.hpp>
#include <smb/montauk.hpp>
#include <smb/mount.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
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 <command> [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 <drive> 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);
}
+64
View File
@@ -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)
+679
View File
@@ -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 <drive> mounted as <drive>:/
// ERR <status> <message> could not mount (status is an smb::Status)
#include <montauk/syscall.h>
#include <montauk/service_log.h>
#include <smb/smb.hpp>
#include <smb/montauk.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
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 <typename Op>
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(&params, 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(&params);
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();
}