# SPEC: scorpiox-scorpioplayer-smb-v1-cifs-file-client (`spsmb1c_`)

A pure C99, zero-dependency, **read-only** SMB 1 / CIFS (dialect `NT LM 0.12`) client for
SCORPIO PLAYER 2027 (row 43). It replaces **SharpCifs.Std 0.2.13** (the jCIFS port), the
library behind the legacy `SMBPlayListFolder` / `SMBNamedStream` /
`SMBCIFSRuntimeConfigHandler`. Crypto (MD4/MD5/HMAC-MD5, RC4, SHA-256/HMAC-SHA256, the
SP800-108 KDF) is vendored with test vectors from MS-NLMP/RFC 1320/1321/2104/2202/4231/
6229; no external library.

The wire shapes mirror the row-45 **SMB2 client**'s proven framing (`scorpiox_io` tunnel,
NBSS, in-process fake server) and the row-44 SMB2 **server**'s NTLM/SPNEGO shapes, which
are interop-proven against smbclient and the Linux kernel CIFS client. The SMB1 packet
layer itself comes from MS-CIFS + the mined SharpCifs IL (the legacy is the spec).

Spec corpora (read-only, frozen commits):

| Short name | File | Commit |
|---|---|---|
| `Handler` | `scorpioxinc.toolkit.std/Handlers/SMBCIFSRuntimeConfigHandler.cs` (142 `SmbFile(FullUrl)`, `ServerPort` default **"22"** bug, `LocalPort` 8137) | `629de26` (2026, "Core 2.0.619, Std 1.1.1") |
| `Folder` | `scorpioxinc.toolkit.std/Folders/SMBPlayListFolder.cs` (`Test(url)` = `ListFiles()` in a try) | same |
| `NamedStream` | `scorpioxinc.toolkit.std/Streams/SMBNamedStream.cs` (74 LOC) | same |
| `Accessor` | `bosxixi.toolkit/…/Toolkit14/MediaOrg/SMBFolderFileAccesssor.cs` (107 LOC, `!IsHidden()` filters, `$ . @` prefix rule) | `e49b5a4` era |
| `SharpCifs` | SharpCifs.Std 0.2.13 IL: `/tmp/sharp.il`, `/tmp/smbfile.il` (+ distilled `/tmp/il_notes.md`, `/tmp/il_wires.md`, `/tmp/il_type*.txt`, `/tmp/il_ntlm*.txt`, `/tmp/il_signing.txt`) | netstandard1.3 build |
| `SmbConstants` | the mined `.cctor` (`DefaultPort` 445, `ResponseTimeout` 30000, `RcvBufSize` 60416, `LmCompatibility` 3, `VcNumber` 1, `NativeLanMan` "jCIFS") | (IL) |

The C# was read only for *behaviour*: settings keys, defaults, the URL form, the hidden
rule and read sizing. The SMB1 protocol itself comes from MS-CIFS (NT LM 0.12) /
MS-SRVS / MS-NLMP / RFC 4178.

## 1. Scope

**In scope:** Direct TCP transport (port 445 default, the legacy `ServerPort` honoured),
NEGOTIATE (`NT LM 0.12` only — the server must pick dialect index 0..10, i.e. the NT
LM 0.12 family), SESSION_SETUP_ANDX with **NTLMv2** (extended security: NTLMSSP inside
SPNEGO NegTokenInit/negTokenResp; non-extended fallback: the raw LMv2 + NTLMv2 response
pair in the lm/nt hash fields, per the task's "NTLMv1/LM refused" rule), guest supported,
TREE_CONNECT_ANDX / TREE_DISCONNECT, share enumeration (`NetShareEnumAll` level 1 over
`\srvsvc` on IPC$ via `TRANS` named-pipe write + `TRANS_PEEK_NAMED_PIPE`/read),
TRANS2 FIND_FIRST2 / FIND_NEXT2 (`FileBothDirectoryInformation`, paged internally until
`EndOfSearch`), NT_CREATE_ANDX (read-only open of a file or directory), READ_ANDX at
64-bit offsets (`OffsetHigh` carried), CLOSE, FIND_CLOSE2, LOGOFF_ANDX, and **SMB1
signing** (MD5, `macSigningKey = sessionKey(16) ++ zeros(24)`) when the server's
SecurityMode says `signing required` (bit 8) — enabled-but-not-required is left unsigned
(the legacy read path never signed; jCIFS only signed when required).

**Out of scope:** every write class (WRITE_ANDX, DELETE, RENAME, CREATE_DIRECTORY,
CHECK_DIRECTORY, SET_INFORMATION*, LOCK, ECHO), NT_TRANSACT, DCE/RPC over anything but
`\srvsvc` on IPC$, Kerberos, DFS referrals, Unicode-only servers without an OEM fallback
negotiated OFF (we always send `Flags2|0x8000` unicode, so this is moot), SMB 2.x/3.x
(separate repos 44-47). **SMB1 is used only when the caller asks for it** — the UI tries
v3 → v2 → v1 and shows a "server is SMB1-only" hint; `spsmb1c_session_json()` carries
`"dialect":"NT LM 0.12"` for exactly that.

## 2. Decisions

**D1. Settings = legacy `RuntimeSettings`, keys unchanged** (`Handler:60-106`):
`HostName` (required), `ServerPort` (int; the legacy default is the **"22"** string bug —
kept as the parse default but 22 is refused by every SMB server, so the *effective*
default is 445 when the key is missing; a bogus non-empty value is `E_INVALID_ARG`),
`LocalPort` (the legacy `jcifs.smb.client.lport`, default 8137 — carried as a bind-hint
*setting only*, not bound: a source port is a per-connection OS detail the C client does
not need and Windows refuses to bind without privilege in some cases; recorded in
`session_json` as `"local_port"`), `UserName`, `Password`, `Path` (`share/sub/dir`),
`FullUrl` (see D2), `DomainName`, `ID`.

**D2. `FullUrl` is parsed when present and wins over HostName/Path**
(`Handler:14,25,39,97-106`: the legacy built `smb://[user:pass@]hostname/path` and fed
`SmbFile(fullurl)`; `SMBPlayListFolder`/`SMBNamedStream` consume exactly that string).
`spsmb1c_url_parse` splits
`smb://[domain;]user:pass@host[:port]/share/sub/dir/` — scheme optional-accept
(`smb:` prefix stripped case-insensitively; a bare `//host/...` also accepted), the
`domain;` and `user:pass@` userinfo split on the FIRST `;` and the LAST `:` inside the
userinfo (a password may contain `:` and `;`? no: jCIFS' `NtlmPasswordAuthentication`
splits userinfo at the first `:` and the first `;`, so a password containing `:` cannot
round-trip — recorded as a legacy limitation, not reproduced), percent-decoding NOT
applied (jCIFS never decoded), the path split at the first `/` after the authority into
`share` + rest, a trailing `/` dropped. `host` may be an IPv6 literal only in brackets
(`Uri.Host` semantics); anything else with `:` before the path is a port. Pure, no
sockets, unit-tested (D-table in tests).

**D3. Guest = empty user AND empty password** (row-45 measured rule, Samba agrees). A
password with an empty user is a real login that the server fails with LOGON_FAILURE —
surfaced as `E_AUTH`, never as "empty folder".

**D4. The hidden rule is the SMB one** (`Folder:53,75` / `Accessor:61-64` files
`IsFile() && !IsHidden()`, folders additionally drop `$ . @` prefixes):
`spsmb1c_is_hidden_name` = first byte `$`, `.` or `@`. `.` and `..` are dropped before the
filter. `list_hidden_count` is what the filter dropped. Files keep `IsHidden()` only
(the `SMBPlayListFolder.GetFilesAsync` line has no `$` check — the `$ . @` rule is the
folder list; the C client applies the SAME filter to both for one deterministic shape and
`list_hidden_count` reports how many were dropped, which the #26 consumer needs).

**D5. Read sizing = the legacy `SmbFile` stream chunking, bounded by the frame.**
jCIFS read in `rcv_buf_size`-ish chunks with `MaxCount` capped at 0xFFFF (READ_ANDX is a
16-bit field; the mined `SmbConstants.RcvBufSize=60416` minus headers ≈ 60k). Ours: one
`spsmb1c_read_at` is capped by `MaxBufferSize - 64` (the negotiated server buffer, minus
the header + a safe margin) and by 0xFF00 (16-bit field minus slack), returns what
arrived — the caller loops to EOF exactly like `SMBNamedStream`/`GetInputStreamAsync`
(the .NET stream model). EOF caps and never pads (the #26 rule).

**D6. Share enumeration when `Path` has no share** (`Handler:79-84` equivalent:
`SmbFile("smb://host/")` lists shares via the LANMAN/RAP `NetShareEnum` — but the legacy
actually called `ListFiles()` on the root URL, which rides the same `\srvsvc` call).
Ours: TREE_CONNECT `\srvsvc`-on-IPC$ → TRANS `NetShareEnumAll` (level 1) → parse the NDR
reply (stub at 24, `EntriesRead`, per-element deferred strings, NUL-terminated names).
`IPC$`/`ADMIN$`/`C$`/`print$` are filtered (row-45 divergence kept: the legacy UI only
showed disk shares). The RAP-level `NetShareEnum` fallback (the pre-NT SMB1 form) is NOT
implemented — every SMB1 server we must serve (Samba 4.x, the NAS) answers the
NT-styled `NetShareEnumAll` over `\srvsvc`; the RAP form only matters for DOS-era
servers this fleet never targets (open question Q3).

**D7. Every failure names its status.** The legacy `SmbFile` threw `SmbException` whose
message was frequently just the class name, and `Test(url)` swallowed it
(`Folder:28-35` — `catch` returns false with no reason). Ours: `spsmb1c_last_error()` is
`"<context>: <STATUS_NAME> (0x%08x)"` for NT statuses or
`"<context>: DOS class <c> code <n>"` for DOS errors, `spsmb1c_last_code()` the API code,
`spsmb1c_last_status()` the raw NTSTATUS or `class|code<<16` DOS value.

**D8. Paging is internal.** FIND_FIRST2 pages at 200 entries (`SearchCount` from the
mined IL) until the reply's `EndOfSearch` flag is 1; FIND_NEXT2 resumes with the search
handle + the last resume key. The caller sees one `spsmb1c_list`. FIND_CLOSE2 is sent on
the early-exit path (item cap) only.

**D9. `FileBothDirectoryInformation` (0x104) is the one info level.** The legacy used
`0x0104` exactly (`ListSize=65535 MaxDataCount, ListCount=200 SearchCount`); the
94-byte fixed part + the UTF-16 name decodes name/size/mtime/attrs. DOS `8.3` short names
in the reply are ignored (the modern server fills them anyway).

**D10. Signing only when required** (`SecurityMode & 8`). `signing_on` then signs every
frame after SESSION_SETUP with `macSigningKey = sessionKey(16) ++ 24 zero bytes`,
MD5 over `key || frame-with-signature-zeroed || seq(ULE32)`, seq starts 0 and the
response counter mirrors it. A server that requires signing but fails our signature is
`E_AUTH` (the legacy jCIFS threw `SmbException("Signature verification failed")`).

**D11. The dialect gate is strict.** NEGOTIATE offers exactly one dialect string,
`NT LM 0.12`, followed by the trailing `0x01` jCIFS quirk byte (mined IL: the `ldstr`
bytearray `02 00 4e 00 54 ... 00 01`). A server that answers a DialectIndex > 10
(i.e. refused NT LM 0.12) is `E_UNSUPPORTED` — the caller moves to the SMB2 client.
`server_caps` without `0x80000000` (extended security) switches the SESSION_SETUP to the
non-extended NTLMv2-response form.

**D12. `max_buffer` governs TRANS2/TRANS sizes.** `MaxParameterCount` 10, `MaxDataCount`
65535 for FIND_FIRST2 (mined), `MaxBufferSize` from the NEGOTIATE reply caps every
TRANS/TRANS2 send (a bigger request is split is NOT supported — the server's
`MaxBufferSize` on every SMB1 server is >= 16 KiB, bigger than anything we send).

**D13. Read-only by construction.** The only commands the client can build are NEGOTIATE,
SESSION_SETUP_ANDX, TREE_CONNECT_ANDX, TREE_DISCONNECT, NT_CREATE_ANDX, READ_ANDX, CLOSE,
FIND_CLOSE2, TRANS2 FIND_FIRST2/NEXT2, TRANS (srvsvc), LOGOFF_ANDX. The write-class
opcodes exist as named constants only so the read-only test can assert no frame ever
carries them (`spb_fake_writes()` counts WRITE_ANDX/DELETE/RENAME/CREATE_DIRECTORY/
CHECK_DIRECTORY/SET_INFORMATION-equivalents; the fake answers them ACCESS_DENIED and
counts).

**D14. The `sprch_handler` boundary is `"SMBCIFS"`** (the legacy `RuntimeType` string,
`Handler:10`) with caps `VALIDATE|LIST|STREAM` (download → `E_NOTSUPPORTED`, the legacy
`DownloadAsync` returned null). `validate` = connect + list shares non-empty (the legacy
`TestSMBConnection` listed the root URL). `stream_url` returns the `smb1://` locator
(same rule as row 45's `smb2://`).

**D15. The `spffa_backend` id is `"smb1"`** (the row-45 `"smb2"` shape): open/list/stat/
locator/close over the vtable, the same `share/sub` vpath split and hidden rule.

**D16. `spsmb1c_connect_json` also accepts `FullUrl`** (the legacy set it and everything
downstream consumed it): when present it overrides HostName/Path via `url_parse`, and
`UserName`/`Password` still win when non-empty (the legacy passed both to
`NtlmPasswordAuthentication`).

**D17. A `sprch` handler is a CALL, never a configuration** (added 1.0.1, 2026-11-22).

Row 45 shipped this fix in 1.0.1 first; this client had vendored the same `h_setup` by copy,
so it carried the same P0. `spsmb1c_use_io()` is process-wide on purpose — that is how an iOS
shell installs its URLSession-backed io once and has every NBSS frame ride it. What must never
happen again is a *call* flipping it. The row-54 handler used to do `spsmb1c_use_io(io)` inside
`h_setup()`, so one `sprch validate` left the client pushing SMB1 frames through whatever
`scorpiox_io` the caller happened to hold. The SCORPIO PLAYER 2027 shell installs **one**
`scorpiox_io_over_http(scorpiox_http_winhttp())` into the sprch registry for every HTTP
engine, so after a validate the SMB1 client posted frames to `smbrpc://HOST:445/frame` through
WinHTTP, and every later `spffa_open("smb1", …)` answered `transport failure` with no network
involved at all. Measured on `.216` for the row-45 sibling (both shipped DLLs, no app
container, same thread, `validate rc=-4` then `open rc=5 'transport'` vs `open rc=0` and two
items without the validate); the SMB3 client (row 47) had the identical line and is fixed in
the same release.

The rule, as shipped in 1.0.1 (`h_scope_begin` / `h_scope_end`, `src/spsmb1c_adapters.c`):

1. Every handler entry point opens a **transport scope** and closes it before returning — on
   the success path *and* on every error path (`h_setup()` closes the scope when it returns
   non-zero, so a bad settings JSON cannot leak the mode either).
2. An **app-installed transport always wins.** If the app already called `spsmb1c_use_io`
   (iOS) or `spsmb1c_use_fake` (tests), the handler leaves it alone. That is what keeps the
   iOS tunnel working end to end.
3. An incoming io is **adopted only when it is this client's own fake face.** `SPB_MODE_SOCK`
   is already the real socket transport; adopting the socket face would replace one connection
   per session with one TCP round trip per SMB1 frame. A foreign io (the registry's
   WinHTTP/URLSession) is not an SMB1 transport and is ignored.
4. `h_scope_end()` drops the call's session through the call's own transport (LOGOFF +
   TREE_DISCONNECT) and then restores the mode and io it found.

`spsmb1c_use_io()` itself is unchanged. `spb_transport_peek` / `spb_transport_restore` /
`spb_transport_rebuild` are internal (hidden visibility, not in `spsmb1c.map`). The regression
test `test_handler_does_not_hijack_transport()` (32 checks) fails **11** of them against the
1.0.0 tree with `transport failure` (and then segfaults on the `{}` row, which strlen'd a NULL
`HostName`) — the P0 reproduced from source.

Two more bugs found while writing the test, both fixed in 1.0.1: `spb_net_io_socket()`
installed `sock_close_v` on a heap `sockctx` (a leak of every socket session's ctx — the heap
face now gets `sock_close_free`), and `spb_sess_ensure()`'s guest-logon retry restored a
vtable whose transport `sess_reset()` had already closed (a use-after-free the fake face
survived only because its close is a no-op — it now calls `spb_transport_rebuild()`).
`h_setup_inner()` also rejects settings with neither `HostName` nor `FullUrl` before reading
them (UBSAN caught the NULL `strlen` on the `{}` row).

## 3. Transports and framing

Same three transports as row 45 (`spb_net.c`):

- **socket** — NBSS over TCP: 4-byte header (`0x00` + 3-byte big-endian length) then the
  32-byte SMB1 header + words + bytes. SMB1 NBSS is the same frame discipline SMB2 uses
  (Samba answers both on 445; port 139 is *not* attempted — jCIFS defaulted to 445 via
  `DefaultPort`).
- **io** — the `scorpiox_io` tunnel (the ONLY transport on iOS): one NBSS frame = one
  `http_post` to `smbrpc://HOST:PORT/frame`, content type `application/x-smb1-nbss+base64`.
- **fake** — the in-process fake SMB1 server (`spb_fake.c`) behind the same `spb_io`
  vtable, so the tests and the console `--test` run every byte through the real framing
  code.

The reader enforces `SPB_FRAME_MAX` (4 MiB) and never allocates from a lying NBSS length.

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

connect → NEGOTIATE (dialect + security mode + capabilities + challenge/GUID+token) →
SESSION_SETUP_ANDX (extended security: type-1 in NegTokenInit → type-2 out → type-3 in
accept-complete; non-extended: LMv2 + NTLMv2 responses with the 8-byte challenge from the
NEGOTIATE reply; guest: the anonymous session) → TREE_CONNECT_ANDX per share (cached,
`Tid` table) → NT_CREATE_ANDX (read-only) → READ_ANDX / TRANS2 → CLOSE → LOGOFF_ANDX.
`spb_sess_drop()` sends LOGOFF_ANDX + TREE_DISCONNECTs, then closes the transport. One
guest retry (transient LOGON_FAILURE) exactly like row 45.

## 5. Limits (bounded decoding everywhere)

| Limit | Value | Why |
|---|---|---|
| one frame | 4 MiB | the biggest legal SMB1 READ_ANDX reply is ~64 KiB; 4 MiB is paranoia |
| search entries | 50,000 | one directory listing |
| shares | 256 | `SPB_MAX_SHARES` |
| trees per session | 8 | `SPB_TREE_MAX` |
| handles | 64 | `SPB_HANDLE_MAX` |
| SPNEGO/NTLM token | 8 KiB | `SPB_TOKEN_MAX` |
| name component | 255 B | SMB1 filename limit |
| path depth / total | 64 / 1024 B | `SPB_DEPTH_MAX` / `SPB_PATH_MAX` |
| FIND page | 200 entries per request | the mined `SearchCount` |
| READ chunk | 0xFF00 | the 16-bit MaxCount field minus slack |

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

`OK 0 / E_NETWORK -1 / E_PROTOCOL -2 / E_AUTH -3 / E_NOTFOUND -4 / E_NO_SESSION -5 /
E_INVALID_ARG -6 / E_LIMIT -7 / E_UNSUPPORTED -8 / E_BUFFER -9 / E_EOF -10 / E_OOM -11`.
Mapping: DOS `ERRbadfile/badpath` (class 2) → `E_NOTFOUND`; DOS `ERRaccess` (class 0
code 5) → `E_AUTH`; DOS `ERRgeneral` (class 1) → `E_PROTOCOL`; DOS class 4 (sharing) →
`E_LIMIT` (a read-only client cannot fix a sharing violation); NT
`LOGON_FAILURE/ACCOUNT_DISABLED/PASSWORD_EXPIRED/ACCESS_DENIED/LOGON_TYPE_NOT_GRANTED` →
`E_AUTH`; NT `OBJECT_NAME_NOT_FOUND/OBJECT_PATH_NOT_FOUND/BAD_NETWORK_NAME` →
`E_NOTFOUND`; NT `MORE_PROCESSING_REQUIRED` is the interim (see Q1); NT
`REQUEST_NOT_SUPPORTED/NOT_SUPPORTED` → `E_UNSUPPORTED`; NT
`USER_SESSION_DELETED/INVALID_HANDLE/FILE_CLOSED` → `E_NO_SESSION`. A `PENDING`
(0x00000103) status on the response is `E_PROTOCOL` — SMB1 has no async interim (unlike
row 45's READ), the reply is either final or the server is broken.

## 7. The fake server (`spsmb1c_use_fake`)

The same tree JSON as row 45's fake (`{"shares":[{"name":…,"root":[…]}],
"users":[{"name":…,"pass":…}],"guest":true}`) so the two engines' test fixtures are
interchangeable. It answers every SMB1 command the client speaks, refuses every
write-class command with ACCESS_DENIED (counted), supports the fault injector
(`sign_required`, `logon_fail`, `no_ipc`, `no_extsec` — the non-extended-security path,
`garbage` n replies, `refuse_nt1`), and its type-3 verify mirrors the row-44 server's
(proof + session key). `no_extsec` is the SMB1-only fault: NEGOTIATE answers with a bare
challenge and the client must walk the non-extended NTLMv2 path.

## 8. Deliberate divergences from the reference implementation

1. **The failures carry reasons.** SharpCifs threw bare `SmbException`s and
   `Test(url)` swallowed them; every C failure names status + context.
2. **No `jcifs.smb.client.lport` bind.** The legacy bound a fixed local port (8137); the
   C client records the setting but lets the OS pick (binding 8137 on a second session
   would collide anyway — the legacy could not open two connections to the same host).
3. **Unicode always.** jCIFS negotiated OEM when the server did not offer unicode; the C
   client sends `Flags2|0x8000` on every frame (Samba 4.15 answers unicode for NT LM 0.12)
   and decodes UTF-16 names; an OEM-only server is `E_UNSUPPORTED` (Q2).
4. **No DFS, no `GetBackupStorage` paths** — the legacy `_enableDfs` resolution is a
   Windows-DC behaviour our fleet never had.
5. **`ServerPort` "22" is not honoured as 22.** The legacy default string is plainly a
   bug (22 is SSH); missing → 445, present-but-junk → `E_INVALID_ARG`, present-and-numeric
   → honoured as-is (even 22, if someone really runs SMB there).

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

- Samba smbd 4.15 NT1 oracle on loopback: shares / deep listing / SHA-256 random reads /
  unicode names — see README "Oracle transcripts".
- impacket 0.13.1 smbserver (SMB1) oracle: the same matrix on a second, independent
  implementation.
- The legacy `FullUrl` parser table (legacy inputs → parsed fields).

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

- **Q1.** `MORE_PROCESSING_REQUIRED` (0xC0000016) as the NEGOTIATE-blob interim (some
  servers answer the first SESSION_SETUP with it) is handled by feeding the reply blob
  back as the next request's token; a server that pings more than 4 interims is
  `E_PROTOCOL`.
- **Q2.** An OEM-only SMB1 server (no `0x8000` unicode) is refused. None exists in the
  fleet (measured 2026-09-23: all SMB1 hosts are Samba/macOS, both unicode-capable); if
  one ever appears, the non-unicode path is a small addition to the string writers.
- **Q3.** The RAP `NetShareEnum` (the DOS-era share list) is not implemented; only the
  `\srvsvc` NT form. Same rationale as D6.
- **Q4.** SMB 2.x/3.x are rows 44-47; when row 46 (SMB3) lands it may vendor this
  framing by copy (no cross-repo dependency), exactly like the server pairs did.
