# SPEC: scorpiox-scorpioplayer-smb-v2-file-client (`spsmbc_`)

A pure C99, zero-dependency, **read-only** SMB 2.0.2/2.1 client for SCORPIO PLAYER 2027
(row 45). It replaces **SMBLibrary 1.5.3.4's `SMB2Client`** (the legacy
`SMB2ClientPortable` path). Crypto (MD4/MD5/HMAC-MD5, SHA-256/HMAC-SHA256, RC4, the
SP800-108 KDF) is vendored with test vectors from MS-SMB2/MS-NLMP; no external library.

The wire shapes mirror the row-44 **server** (`scorpiox-scorpioplayer-smb-v2-file-server`),
which is interop-proven against smbclient and the Linux kernel CIFS client — the client
parses what that server (and Samba 4.15, measured) emits.

Spec corpora (read-only, frozen commits):

| Short name | File | Commit |
|---|---|---|
| `SMB2ClientPortable` | `scorpioxinc.toolkit.std/SMB2ClientPortable.cs` | `de7c179` (2025-06-07) |
| `Handler` | `scorpioxinc.toolkit.std/Handlers/SMB2RuntimeConfigHandler.cs` | same |
| `Folder` | `scorpioxinc.toolkit.std/Folders/SMB2PlayListFolder.cs` | same |
| `NamedStream` | `scorpioxinc.toolkit.std/Streams/SMB2NamedStream.cs` | same |
| `MyISmbFile` | `scorpioxinc.toolkit.std/MyISmbFile.cs` (`IsHidden` forwards to SharpCifs) | same |
| `Seekable` | `bosxixi.toolkit/bosxixi.ScorpioPlayer.Core/Toolkit14/SeekableStream/SeekableSMB2Stream.cs` | `ddd28c7` (2023-09-18) |
| `Accessor` | `…/Toolkit14/MediaOrg/SMBFolderFileAccesssor.cs` (`!IsHidden()` filters) | same |
| `StoreWrapper` | `bosxixi.toolkit20/SMBFileStoreWrapper.cs` | `35dc5bd7` era |
| `Samba` | the `IPlayListFolder` hidden rule audit (picobot task
  `scorpioplayer-playlist-folder-model-dll-oneshot.md` §"five hidden-entry rules") | (task) |

The C# was read only for *behaviour*: settings keys, defaults, the hidden rule and read
sizing. The SMB protocol itself comes from MS-SMB2 / MS-NLMP / RFC 4178 / MS-SRVS.

## 1. Scope

**In scope:** Direct TCP transport (port 445 default), NEGOTIATE (2.0.2, 2.1 — offered in
that order, the server picks), SESSION_SETUP with NTLMv2 inside SPNEGO (guest supported),
TREE_CONNECT / TREE_DISCONNECT, share enumeration (`NetShareEnumAll` level 1 over `\srvsvc`
on IPC$ via `FSCTL_PIPE_TRANSCEIVE`), QUERY_DIRECTORY (`FileIdBothDirectoryInformation`,
paged internally), CREATE (read-only open of a file or directory), READ at 64-bit offsets
(capped per frame by the credit rules), CLOSE, LOGOFF, signing (HMAC-SHA256, 2.0.2 session
key verbatim / 2.1 SP800-108 KDF).

**Out of scope:** every write class (WRITE, SET_INFO, LOCK, FLUSH, CHANGE_NOTIFY, ECHO,
CANCEL, OPLOCK_BREAK), SMB1, SMB 3.x (encryption, 3.1.1 pre-auth), Kerberos, DFS
referrals, named streams beyond the locator. SMB 1 and SMB 3 are separate repos
(rows 42/43 and 46/47).

## 2. Decisions

**D1. Settings = legacy `RuntimeSettings`, keys unchanged** (`SMB2ClientPortable.cs:17-25`,
`Handler:33-35`): `HostName` (required), `UserName`, `Password`, `Path` (`share/sub/dir`),
`DomainName`, `ID`. `spsmbc_connect_json` parses exactly these keys, `Path` is split by the
first `/` or `\` into share + sub-path (`Handler:33-35`: `Trim('/').Trim('\\')`, split,
first = TreeConnectPath, rest = Path). Junk `Port` → `E_INVALID_ARG` (the legacy passed
no port at all).

**D2. Empty user AND empty password = guest** (`SMB2ClientPortable.cs:31` passes whatever it
has; SharpCifs' `NtlmAuthenticator` anon path). A password with an empty user is a *real*
login that the server fails — that is the row-44 server's measured rule and Samba agrees.

**D3. The read sizing is MaxReadSize, not the legacy 16 KiB floor.**
`SeekableSMB2Stream.cs:159` reads `Math.Min(remaining, Math.Max(16384, MaxReadSize))` per
call, so the legacy loop *floors* at 16 KiB but never exceeds MaxReadSize. Ours: one
`spsmbc_read_at` is capped by `MaxReadSize` and by the credit rule (one credit ⇒ ≤ 65536
bytes without LargeMtu), and returns what arrived — the caller loops to EOF, exactly like
`SeekableSMB2Stream.Read` (`Math.Min(Length - Position, count)`, the EOF cap).

**D4. A READ never charges more than one credit** (Samba 4.15 measured: *“client used more
credits than granted, charge 2, credits_granted 1”* kills the connection). With
LargeMtu negotiated, `want` is still capped at 65536 per frame unless the reply's granted
credits allow more; `MaxReadSize` (1048576 on the fake) is honoured as the reply-side cap.

**D5. The hidden rule is the SMB one** (`SMBPlayListFolder.cs:53,75` files
`IsFile() && !IsHidden()`, folders `IsDirectory() && !IsHidden()`; the SharpCifs rule is
`$ . @` prefixes): `spsmbc_is_hidden_name` = first byte `$`, `.` or `@`. `.` and `..` are
dropped before the filter (they are never entries in our model). `list_hidden_count` is
what the filter dropped. `.DS_Store` is a **file** and stays visible (the #26/row-27
legacy-rule note in the folder-file-accessor task).

**D6. Share enumeration when `Path` has no share** (`Handler:79-84`: `ListShares`).
`\\s\IPC$` is joined, `\srvsvc` opened, `NetShareEnumAll` level 1 sent, the NDR reply
parsed (stub at 24, `EntriesRead`, per-element deferred strings, NUL-terminated names).
`IPC$` itself is filtered out of the result (it is the pipe, not a share). Windows/Samba
both list it; the legacy `ListShares` also returned it, but the player only shows disk
shares.

**D7. Every failure names its NTSTATUS.** The legacy `Connect`+`Login` returned `null`
with no reason (`SMB2ClientPortable.cs:28-36`). Ours: `spsmbc_last_error()` is
`"<context>: <STATUS_NAME> (0x%08x)"`, `spsmbc_last_code()` the API code,
`spsmbc_last_ntstatus()` the raw NTSTATUS (0 when the failure was not NT-mapped).

**D8. Paging is internal.** QUERY_DIRECTORY pages at 50 entries (`fake` rule; Samba
replies `STATUS_NO_MORE_FILES` at the buffer end) until the server says `NO_MORE_FILES`;
the caller sees one `spsmbc_list`. `spsmbc_list_pages` is not exposed — the #26 consumer
only needs count + json.

**D9. One global session** (`spc_sess g_s`), not thread-safe, the fleet shell serialises
calls. The sprch handler and the spffa backend use the same session by design (the row-54
handler is a thin view over `spsmbc_*`).

**D10. Transports** (SPEC section 3): `spsmbc_use_sockets` (default, real TCP),
`spsmbc_use_io` (NBSS frames tunnelled one `http_post` each through `scorpiox_io`,
`smbrpc://host:port/frame`, base64 body — the ONLY transport on iOS), `spsmbc_use_fake`
(the in-process fake server). `spsmbc_io_socket` / `spsmbc_io_fake` expose the same faces
as `scorpiox_io` for the app-side vtable.

## 3. Transports and framing

NBSS: one unit = type byte 0 + 3-byte big-endian length + the SMB2 frame. `spc_net_frame`
writes one unit and reads one; a zero-length unit from the peer is a keepalive and the
reader re-reads. **The async-interim read passes `req == NULL` and writes nothing**
(the interim handler only reads; an earlier build wrote a 4-byte zero-length unit, which
Samba treats as protocol noise and drops the connection — measured 1-in-10, fixed).

## 4. The state machine (`spc_sess_ensure`)

```
connect -> NEGOTIATE (2.0.2/2.1 offered, signing mode honoured, caps/MaxRead/MaxWrite kept)
        -> SESSION_SETUP leg 1 (NTLM NEGOTIATE_MESSAGE inside SPNEGO NegTokenInit)
        -> leg 2: the server's NTLMSSP_CHALLENGE parsed (target info, flags, challenge)
           -> NTLMv2 AUTHENTICATE_MESSAGE -> NTStatus SUCCESS (or the failure named)
        -> (share calls) TREE_CONNECT per share, IPC$ on demand, TREE_DISCONNECT at logoff
```

Credits: the balance starts at 1, every reply's `Credit` grants back, every request's
`CreditCharge` spends. The fake grants 2 per reply; Samba grants 1–32.

## 5. Limits (bounded decoding everywhere)

| Limit | Value | Where |
|---|---|---|
| frame | 4 MiB | `SPC_FRAME_MAX` |
| path | 1024 | `SPC_PATH_MAX` |
| share name | 80 | `SPC_NAME_MAX` |
| list entries | 50000 | `SPC_MAX_ITEM` |
| shares | 256 | `SPC_MAX_SHARES` |
| trees per session | 8 | `SPC_TREE_MAX` |
| open handles | 64 | `SPC_HANDLE_MAX` |
| NTLM token | 8192 | `SPC_TOKEN_MAX` |
| depth | 64 | `SPC_DEPTH_MAX` |
| search pattern | 512 | `SPC_PAT_MAX` |

## 6. Error taxonomy (frozen, `include/spsmbc.h`)

| Code | From |
|---|---|
| `E_NETWORK` -1 | refused, reset, timeout, DNS, `no NBSS header`, interim timeout |
| `E_PROTOCOL` -2 | malformed/truncated/unexpected reply, `INVALID_PARAMETER`, mid mismatch |
| `E_AUTH` -3 | `LOGON_FAILURE`, `ACCESS_DENIED`, `WRONG_PASSWORD` |
| `E_NOTFOUND` -4 | `OBJECT_NAME_NOT_FOUND`, `OBJECT_PATH_NOT_FOUND`, `BAD_NETWORK_NAME` |
| `E_NO_SESSION` -5 | not connected, `USER_SESSION_DELETED`, `NETWORK_SESSION_EXPIRED` |
| `E_INVALID_ARG` -6 | bad host/share/path/handle/offset/buffer/settings |
| `E_LIMIT` -7 | decode limit exceeded (frame > 4 MiB, > 50000 entries, > 64 handles) |
| `E_UNSUPPORTED` -8 | the server refused both 2.x dialects, fsctl unsupported |
| `E_BUFFER` -9 | caller out-buffer too small (sprch list/stream) |
| `E_EOF` -10 | read past EOF |
| `E_OOM` -11 | allocation failure |

The NTSTATUS → API map lives in `st_map` (`src/spc_sess.c`); unknown NTSTATUS keeps
`E_PROTOCOL` and the raw code in the message.

## 7. The search pattern

A leaf name only — no separator, bounded (512 bytes), printable; `*` and `?` glob,
case-insensitive ASCII, bytes ≥ 0x80 compare exactly (`src/spc_util.c`). The legacy passed
`"*"` (`SMB2ClientPortable.cs:48`) — the wildcard is expanded by the *server* for SMB.

## 8. The `sprch_handler` (row 54) and `spffa_backend` (#26)

`spsmbc_sprch_handler()` returns the row-54 vtable with `runtime_type = "SMB2"`,
caps `0x23` (VALIDATE | LIST | STREAM | CAPS): `validate` = the legacy
`TestSMB2Connection` (connect + negotiate + a share probe, a fresh `ID` in the reply),
`list` = browse (`share[/sub]`), `stream_url` = the range-readable locator
(`smb://host:port/share/path`), `download` → `SPRCH_E_NOTSUPPORTED` (read-only client).
Settings JSON keeps the legacy `RuntimeSettings` key names.

`spsmbc_spffa_backend()` returns the #26 storage vtable (`id "smb2"`, `CAP_STAT`,
struct_size 72): the folder accessor drives the same `spsmbc_*` calls.

## 9. Deliberate divergences from the reference implementation

| # | Legacy (C#) | Ours | Why |
|---|---|---|---|
| D9a | `Connect`+`Login` return `null`, no reason | every failure names the NTSTATUS | the player showed "Object reference not set" for a dead server |
| D9b | 16 KiB read floor | MaxReadSize/credit-capped reads, caller loops | 100× fewer frames on loopback (measured: 353 MB/s vs the 16 KiB floor) |
| D9c | `FileDirectoryInformation` class | `FileIdBothDirectoryInformation` | the fake + Samba both speak it; the fileid makes the deterministic byte pattern stable |
| D9d | `IsHidden()` via SharpCifs (style bits) | the `$ . @` first-byte rule | the playlist-folder audit: five different rules; SMB's own one is `$ . @` |
| D9e | empty folder → `null` → NRE | count 0 + `[]` | #26 fixes the model |
| D9f | no guest handling (anon = empty DOMAIN/user) | empty user AND empty password = guest | the row-44 + Samba rule |
| D9g | writes refused by AccessMask | no write-class command is even built | read-only by construction |

## 10. The fake server (`spsmbc_use_fake`)

The tree comes from JSON (`src/spc_fake.c` header): `shares` (name + `root` array), nodes
with `children`, `size`, `mtime`, `text`; `users` (name/pass) and `guest: true`.
Commands: NEGOTIATE, SESSION_SETUP (raw NTLM + SPNEGO), TREE_CONNECT, TREE_DISCONNECT,
CREATE, READ, QUERY_DIRECTORY (FileIdBothDirectoryInformation, `NextEntryOffset` chain,
50-entry pages), IOCTL (`FSCTL_PIPE_TRANSCEIVE` on `\srvsvc` with a real DCERPC
bind/bind_ack + `NetShareEnumAll` level 1 reply), CLOSE, LOGOFF. File bytes are
deterministic: `(fileid*31 + off*7 + (off>>8)) & 0xFF` (a `text` node returns its bytes).
Faults via `spsmbc_fake_set_fault(what, n)`: `sign_required`, `refuse_202`, `garbage`,
`logon_fail`, `no_ipc`, `page` (entries per page), `reset_counts`. Call counters via
`spsmbc_fake_calls(cmd)` — the read-only proof asserts no write-class command was ever
sent.

## 11. Measured (full tables in README / the report)

- **Samba smbd 4.15** (loopback 1445, `server max protocol = SMB2_10`, `aio read size = 0`):
  shares, ls, cat, sha, ranges — all equal to disk; 30/30 clean `ranges` runs.
- **impacket smbserver 0.13.1** (loopback 2445, `SMB2Support = yes`): shares, ls, cat, sha,
  ranges — all equal to disk.
- **Throughput** vs the legacy 16 KiB floor: 1 MiB in one pipelined chain on the fake;
  353 MB/s over loopback on smbd for a 3 MiB file (53 frames).
- **ASAN + UBSAN clean** (`make asan`), 156 unit checks, 60 fuzz corpus files clean.

## 12. Open questions (written down, not guessed)

- **Q1.** SMB 3.0/3.0.2/3.1.1 is row 46/47. When it lands it may vendor this framing by
  copy (no cross-repo dependency).
- **Q2.** Multi-credit pipelining (several requests in flight) is built into the frame
  layer (`spc_credit_charge`, the credit balance) but the public API is synchronous; a
  future `spsmbc_readv` could pipeline a range list.
- **Q3.** Lease/oplock state is ignored (read-only client, `OPLOCK_BREAK` never handled);
  a caching layer (row 27's `folder-file-accessor` decides) would need it.
- **Q4.** DFS referrals (`DFS_OPERATION` in `\srvsvc`) are not followed; a DC with only
  DFS targets would need row 46.
