/* * smb.hpp * SMB2/SMB3 client library * Copyright (c) 2026 Daniel Hammer */ #pragma once #include #include // A small blocking SMB client: one TCP connection, one session, one request // in flight. It speaks SMB 2.0.2, 2.1, 3.0 and 3.0.2 with NTLMv2 // authentication (inside SPNEGO) and message signing; no SMB1, no Kerberos, // no SMB3 encryption (a server or share that demands encryption is refused // with ERR_UNSUPPORTED). // // The library does no I/O of its own. The caller supplies a connected byte // stream and a random source through smb::Io, which keeps it portable: the // same sources build for MontaukOS (smbfs.elf, smb.elf) and for the host test // harness in tests/smb. It needs malloc/free, and BearSSL's hash, // HMAC and AES primitives. // // Paths are UTF-8 and relative to the share root; '/' and '\' both separate // components and a leading separator is ignored ("" is the share root). // Times are UTC unix seconds. namespace smb { enum Status : int { OK = 0, ERR_IO = -1, // connection lost or could not send/receive ERR_TIMEOUT = -2, // server did not answer in time ERR_PROTOCOL = -3, // malformed or unexpected server message ERR_AUTH = -4, // logon refused (bad user or password) ERR_ACCESS = -5, // access denied ERR_NOT_FOUND = -6, // no such file or directory ERR_EXISTS = -7, // name already exists ERR_NOT_EMPTY = -8, // directory not empty ERR_IS_DIR = -9, ERR_NOT_DIR = -10, ERR_BUSY = -11, // sharing violation / file in use ERR_NO_SPACE = -12, ERR_UNSUPPORTED = -13, // server needs something this client lacks ERR_BAD_SHARE = -14, // no such share on the server ERR_NOMEM = -15, ERR_INVALID = -16, // invalid argument or name ERR_SIGNATURE = -17, // a signed server message failed verification ERR_READ_ONLY = -18, ERR_FAILED = -19 // any other server error (see last_nt_status) }; // Short English description of a Status, for messages and logs. const char* status_text(int status); // Byte stream to the server plus a random source. struct Io { void* ctx; // Send exactly `len` bytes. Returns 0, or -1 if the connection failed. int (*send)(void* ctx, const void* data, uint32_t len); // Receive up to `len` bytes, waiting at most timeoutMs for the first. // Returns the count (> 0), 0 on timeout, or -1 if the connection closed. int (*recv)(void* ctx, void* buf, uint32_t len, uint32_t timeoutMs); // Fill `buf` with cryptographically random bytes. void (*random)(void* ctx, void* buf, uint32_t len); }; // An empty user logs on as guest, falling back to an anonymous session. // `domain` may be empty. The strings are only read during connect(). struct Credentials { const char* user; const char* password; const char* domain; }; struct FileId { uint8_t raw[16]; }; struct FileInfo { uint64_t size; int64_t mtime; int64_t ctime; // creation time int64_t atime; uint32_t attributes; // ATTR_* bool isDir; }; static constexpr uint32_t ATTR_READONLY = 0x01; static constexpr uint32_t ATTR_HIDDEN = 0x02; static constexpr uint32_t ATTR_SYSTEM = 0x04; static constexpr uint32_t ATTR_DIRECTORY = 0x10; struct DirEntry { char name[768]; // UTF-8 FileInfo info; }; struct ShareInfo { char name[256]; // UTF-8 char comment[256]; uint32_t type; // SHARE_TYPE_* in the low bits bool hidden; // administrative / special share (C$, IPC$, ...) }; static constexpr uint32_t SHARE_TYPE_DISK = 0; static constexpr uint32_t SHARE_TYPE_PRINTER = 1; static constexpr uint32_t SHARE_TYPE_DEVICE = 2; static constexpr uint32_t SHARE_TYPE_IPC = 3; // How to open a file (open()). enum OpenMode : int { OPEN_READ = 0, // existing file, read only OPEN_READWRITE, // existing file, read and write OPEN_CREATE, // create or truncate, read and write OPEN_CREATE_NEW // create, fail with ERR_EXISTS if present }; // Largest read or write one request carries; larger calls are split. static constexpr uint32_t MAX_IO = 65536; struct Client { Io io; bool connected; uint16_t dialect; // 0x0202, 0x0210, 0x0300, 0x0302 bool signing; // requests are signed, responses verified bool guest; // logged on as guest or anonymously uint8_t signingKey[16]; uint64_t sessionId; uint64_t messageId; uint32_t maxRead; uint32_t maxWrite; uint32_t maxTransact; uint32_t timeoutMs; // per-request answer timeout uint32_t lastNtStatus; // NTSTATUS of the last failed request char server[256]; // name used in \\server\share paths uint8_t* buf; // message buffer (request, then response) uint32_t bufCap; uint32_t respLen; // length of the response held in buf bool serverRequiresSigning; }; // ---- Session ---- // Negotiate and log on over an already connected stream. `serverName` is // the host name or address the user gave (used for share paths). On // failure the client is left disconnected; call disconnect() regardless // to free its buffer. int connect(Client* c, const Io& io, const char* serverName, const Credentials& creds); // Log off (best effort) and free the client's buffer. The caller closes // the underlying stream. void disconnect(Client* c); // Round trip to the server; ERR_IO / ERR_TIMEOUT mean the link is dead. int echo(Client* c); // ---- Shares ---- int tree_connect(Client* c, const char* share, uint32_t* outTreeId); int tree_disconnect(Client* c, uint32_t treeId); // List the server's shares (srvsvc NetrShareEnum over IPC$). Returns the // number written to `out` (at most `max`) or a negative Status. int list_shares(Client* c, ShareInfo* out, int max); // ---- Files ---- int open(Client* c, uint32_t tree, const char* path, OpenMode mode, FileId* outId, FileInfo* outInfo = nullptr); int close(Client* c, uint32_t tree, const FileId& id); // Read / write up to `len` bytes at `offset`. Returns the byte count // (0 at end of file) or a negative Status. int read(Client* c, uint32_t tree, const FileId& id, uint64_t offset, void* buf, uint32_t len); int write(Client* c, uint32_t tree, const FileId& id, uint64_t offset, const void* buf, uint32_t len); // Current size of an open file. int file_size(Client* c, uint32_t tree, const FileId& id, uint64_t* outSize); // ---- Namespace ---- int stat(Client* c, uint32_t tree, const char* path, FileInfo* out); // Enumerate a directory ("." and ".." are skipped). The callback returns // false to stop early. Returns the number of entries delivered or a // negative Status. typedef bool (*DirCallback)(void* ctx, const DirEntry& entry); int list_dir(Client* c, uint32_t tree, const char* path, DirCallback cb, void* ctx); int mkdir(Client* c, uint32_t tree, const char* path); // Remove a file or an empty directory. int remove(Client* c, uint32_t tree, const char* path); // Rename / move within the share. Fails with ERR_EXISTS if `to` exists // unless `replace` is set. int rename(Client* c, uint32_t tree, const char* from, const char* to, bool replace = false); // Set access / modification times; a time of 0 is left unchanged. int set_times(Client* c, uint32_t tree, const char* path, int64_t atime, int64_t mtime); // ---- Helpers shared with the tools ---- // Split "smb://[domain;]user@host[:port]/share/sub/dir" or // "//host/share/sub" or "\\host\share" into its parts. Missing parts come // back empty (port 0). Returns false if there is no host. struct Url { char host[256]; char share[256]; char path[512]; char user[128]; char domain[128]; int port; }; bool parse_url(const char* text, Url* out); }