# SPEC: scorpiox-scorpioplayer-nfs-v3-file-client (`spnfsc_`)

A pure C99, zero-dependency, **read-only** NFS v3 client for SCORPIO PLAYER 2027. It replaces
the vendored C# `NFSLibrary`, which is 46,924 lines in `tplayer/bosxixi.Toolkit20/NFSLibrary/`,
vendored 2022-12-08 in `35dc5bd7`. That library bundles a RemoteTea ONC/RPC port (LGPL 2).

**Written from the RFCs only**: RFC 5531 (ONC RPC v2), RFC 4506 (XDR), RFC 1833 (portmapper v2)
and RFC 1813 (NFS v3 + MOUNT v3). No RemoteTea code was read for implementation or translated.
The C# was read only for *behaviour*: settings keys, defaults, the hidden rule and read sizing.

Spec corpora, all read-only. Line numbers are at the frozen commits:

| Short name | File | Commit |
|---|---|---|
| `NFS.cs` | `bosxixi.toolkit/bosxixi.ScorpioPlayer.Core/Toolkit14/NFS/NFS.cs` | `ddd28c7` (2023-09-18) |
| `Seekable` | `…/Toolkit14/SeekableStream/SeekableNFSStream.cs` | same |
| `Accessor` | `…/Toolkit14/MediaOrg/NFS2FolderFileAccesssor.cs` | same |
| `Connectors` | `…/Toolkit14/Connectors/ConnectorsExtension.cs` | same |
| `Handler` | `scorpioxinc.toolkit.std/Handlers/NFSRuntimeConfigHandler.cs` | `de7c179` (2025-06-07) |
| `Folder` | `scorpioxinc.toolkit.std/Folders/NFS2PlaylistFolder.cs` | same |
| `NamedStream` | `scorpioxinc.toolkit.std/Handlers/FTPRuntimeConfigHandler.cs:374-428` (`NFSNamedStream`) | same |
| `Wrapper` | `tplayer/bosxixi.Toolkit20/Class1.cs` (`NFSClientWrapper`) | `71ca80f` |
| `NFSClient` / `NFSv3` | `tplayer/bosxixi.Toolkit20/NFSLibrary/{NFSClient.cs, Protocols/V3/NFSv3.cs}` | `35dc5bd7` |
| template | the live `runtimetemplatebundle.txt`, page `NFSEdit` | (template-parse console testdata) |

## 1. Scope

**In scope:** portmapper `GETPORT`, the MOUNT v3 procedures `EXPORT`, `MNT` and `UMNT`, and the
NFS v3 procedures `GETATTR`, `LOOKUP`, `READLINK`, `READ`, `READDIRPLUS`, `READDIR` and `FSINFO`.
RPC runs over TCP with record marking, and over UDP for the portmapper and for a MOUNT that is
registered only on UDP. Credentials are AUTH_SYS, with AUTH_NONE for the portmapper.

**Out of scope:** any write procedure, NFS v2, NFS v4.x, NLM locking and Kerberos (RPCSEC_GSS).
A `NFSVersion` of `v2` or `v4` gets `SPNFSC_E_UNSUPPORTED` with the message *"this client speaks
NFS v3 only"*. The legacy code accepted both (`Connectors:15-18`). v2 is dead, and v4.1 would
be a separate repo if it is ever needed.

## 2. Decisions

**D1. Settings = legacy `RuntimeSettings`, keys unchanged** (`Connectors:14-22`, template `NFSEdit`).

| Key | Legacy default | Ours |
|---|---|---|
| `HostName` | required (`Connectors:23`, returns null if empty) | required, else `E_INVALID_ARG` |
| `NFSVersion` | `"v3"` (`Enum.TryParse`) | `v3`/`3` accepted; anything else `E_UNSUPPORTED` |
| `Path` | not read by `TryGetNFSClient`; the template has it | when set, the browse root is this export (§D14) |
| `UserID` / `GroupID` | `int.Parse(IfEmptyUse("0"))`, which throws on junk | `0`; junk → `E_INVALID_ARG` (no throw) |
| `CommandTimeout` | `60000` | the same (ms, per RPC) |
| `Encoding` | **`Encoding.ASCII`** if empty (`Connectors:55`); a number = codepage | **UTF-8** if empty (task decision). Names: `utf-8`, `gbk`/`gb2312`/`936`/`gb18030`, `big5`/`950`, `latin1`/`1252`, `ascii`, else `E_CHARSET` |
| `UseSecuePort` (sic) | **`true`** (`Connectors:74`, template default `True`) | the same default; see D8 |
| `UseCache` | `false` | the same; a LOOKUP handle cache (D13) |
| `MountPort`, `NFSPort` | (new) | optional fixed ports for a server whose rpcbind is closed (D4) |

Booleans follow `bool.Parse`: they are case-insensitive, whitespace is trimmed and an empty
string takes the default. The template's `NFSVersion` shows up twice (a TextBox plus a
MultiValue). That is the template's problem, not ours.

**D2. The procedure table is the safety mechanism.** `nx_procs[]` (`src/spnfsc_xdr.c`) lists 14
(program, version, procedure) triples, and `build_call()` refuses anything that is not in it
*before any byte is built*. No write procedure (`SETATTR WRITE CREATE MKDIR SYMLINK MKNOD REMOVE
RMDIR RENAME LINK COMMIT`), no `MOUNTPROC3_UMNTALL` and no portmapper `SET`/`UNSET` exist.
`ACCESS` was dropped as well, because nothing needs it (open errors come from `READ`).
Three things assert this:
`spnfsc_xdr_selftest` case 18, `test_unit` (`proc_table_json` has no write name,
and `proc_is_write ∧ allowed` is never true for procs 0-21), and the fake server's call
counters (zero write calls after the full suite). The legacy library has
`CreateDirectory/DeleteFile/Write/Move/SetFileSize` (`NFSClient.cs:291-702`), and the player
never called them.

**D3. Transport seam.** The RPC layer talks to an `nx_tx` with `call` (one RPC) and an
optional `callv` (k RPCs pipelined on one TCP connection, matched by XID). There are three:
- **sockets** (default), with POSIX + Winsock in one file.
- **`scorpiox_io` tunnel**, so iOS or any shell that owns sockets can carry it. It uses one
  `http_post` per RPC. The URL is `nfsrpc://HOST:PORT/tcp|udp`, the body is the base64 RPC call
  message and the content type is `application/x-onc-rpc+base64`. A 200 body is the base64
  reply. 401/403 → `E_AUTH`, other statuses → `E_NETWORK` and bad base64 → `E_PROTOCOL`.
  `spnfsc_io_socket()` is the matching server side, so a shell can hand it straight back.
  This is the only way the sprch handler talks, because the sprch boundary mandates
  `scorpiox_io` as the only transport.
- **fake**: an in-process portmapper + MOUNT + NFS server (§11). It decodes real call bytes
  and encodes real replies.

**D4. Port discovery.** A `GETPORT` for MOUNT v3/TCP goes out over TCP to 111, with UDP as the
fallback. If MOUNT is not registered on TCP, the client asks for UDP. NFS v3/TCP goes through
`GETPORT` too. If the portmapper is unreachable the client falls back to **2049** (RFC 1813
§1.3 convention). If it answers "0" (not registered), the error is *"v4-only server?"*
`E_UNSUPPORTED`. `MountPort`/`NFSPort` (or `spnfsc_set_ports`) skip the portmapper
entirely. The legacy code used the portmapper for both, and put MOUNT on **UDP** and NFS on
TCP (`NFSv3.cs:54,60`).

**D5. Listing = `READDIRPLUS`, paged**, with cookie + cookieverf, `dircount` 32 KiB and
`maxcount` 256 KiB. If the first page gets `NFS3ERR_NOTSUPP`, the session switches to
`READDIR` + per-entry `LOOKUP` (+ `GETATTR` when LOOKUP carries no attributes). An entry that
vanishes between READDIR and LOOKUP is dropped, not reported. `NFS3ERR_BAD_COOKIE` in the
middle of a listing → `E_PROTOCOL` "directory changed while listing". The whole listing fails,
and a partial list is never returned. The legacy client used `READDIR` with `Count = 4096`
(`NFSv3.cs:195`), and then **one LOOKUP per entry to decide `IsFolder`** (`NFS.cs:160`). That
is 20,001 round trips for a 20k-entry folder. Ours makes 12 pages and 17 RPCs in total on
kernel-nfsd, including connect and mount.

**D6. The listing model.** `.` and `..` are dropped. So is any name that is empty or contains
`/` or NUL, because it can never be a valid entry and would break path joins. Entries are
**sorted by byte order** of the UTF-8 name, so two listings are identical (and the #26
determinism checks hold). The legacy code kept server order. Each item carries: `name`, `path`
(relative to the export, `/`-joined), `folder`, `kind` (file/folder/symlink/…), `size` (**-1 for
folders**, #26 decision #7), `mtime_ms` (with ns→ms), `fileid`, `hidden` and `mode`.

**D7. AUTH_SYS.** The machinename is the fixed `"scorpioplayer"`. The legacy code sent the
**server's** IP there (`NFSv3.cs:52`), which is meaningless but harmless. We never send the
local host name, because it identifies the user. The stamp is the time, and gids = [gid].

**D8. `UseSecuePort` and privilege.** When the setting is on, the socket binds a source port in
1023…600 before `connect`. The legacy code picked random ports in 665-1022 and probed them
with a `TcpListener` (`OncRpcTcpClient.cs:245-266`). If the bind fails (`EACCES`, not root, no
`CAP_NET_BIND_SERVICE`, or every port in use), the client **falls back to an ephemeral port
and records it** (`secure_port_fell_back` in `fsinfo_json`). If the server then refuses:
- an RPC `AUTH_ERROR/AUTH_TOOWEAK` → `E_PRIVILEGE` with *"it may require a reserved source port"*
- a `MNT3ERR_ACCES` after a fallback → `E_PRIVILEGE` with *"needs root/CAP_NET_BIND_SERVICE; the
  export probably has the 'secure' option"*

The CLI defaults to `--insecure`, so it runs unprivileged. Tests never need root: the fake
emulates `AUTH_TOOWEAK`, and the loopback oracle exports with `insecure`.

**D9. Read sizing: the reason NFS playback was slow.** The legacy path is
`SeekableNFSStream.Read` → `ReadPartial(count ≤ 16384)` (`Seekable:11,57`) → **one** READ for
`Math.Min(rcount - totalRead, 16384)` bytes, one RPC in flight at a time. `NFSClient` fixes its
own block size at 7,900 (`NFSClient.cs:50-56`). `GetBlockSize()` (`NFSv3.cs:86-111`) raises it
after mount, but caps it at **65336** (a typo for 65536), so even a 1 MiB-rtpref server gets
≤ 64 KiB. `SeekableNFSStream` never used that path anyway: it goes through `ReadPartial` with
16 KiB. Ours:
- rsize = `FSINFO.rtpref`, clamped to `[4 KiB, min(rtmax, 1 MiB)]`, or `spnfsc_set_rsize`.
- `read_at(off, count)` splits into rsize READs and keeps **up to 8 in flight** on one TCP
  connection (`spnfsc_set_pipeline`, 1..32). Replies are matched by XID, in any order: the
  fake answers in reverse to prove it.
- A short READ without EOF resumes from where it stopped. EOF (or `count = 0`) ends the read
  at the real end.
- **EOF cap** (`Seekable:50` `Math.Min(Length - Position, count)`): `read_at` never returns
  bytes past the size known at `open`. Offset ≥ size → 0.
- `spnfsc_legacy_block_size()` reproduces the C# formula exactly, for the report.

**D10. Retry policy.** `NFS3ERR_JUKEBOX` is retried 5 times with backoff (50 ms × 2ⁿ, cap
1.6 s), and then → `E_SERVER` "server busy". Before `JUKEBOX` goes on the wire, XID `STALE`
during `READ` or a listing gets **one** re-resolution by path from the export root. The LOOKUP
cache is dropped first. A TCP connection that was cached and turns out closed is reopened once.
On UDP, the request is retransmitted with 500 ms → 4 s backoff inside `CommandTimeout`, and
the same XID is used, so the server's duplicate request cache can recognise the retransmit.

**D11. Bounded decoding.** Every length in a reply is checked before use:

| What | Limit | Error |
|---|---|---|
| one RPC record (all fragments) | 8 MiB | `E_LIMIT` |
| file handle | 64 bytes (`NFS3_FHSIZE`) | `E_LIMIT` |
| names in a directory entry | 1,020 bytes | `E_LIMIT` |
| export dir / group / readlink target | 4,096 bytes | `E_LIMIT` |
| READ data | 4 MiB, and ≤ the requested count, and == the `count` field | `E_PROTOCOL` |
| entries per page / per listing | 100,000 / 2,000,000 | `E_LIMIT` |
| exports / groups per export | 10,000 / 10,000 | `E_LIMIT` |
| an empty page without EOF | 0 | `E_PROTOCOL` (a server that loops forever) |

Recursion is not used anywhere. A `bool` that is not 0/1 and an `ftype3` outside 1..7 are
protocol errors. A length of `0xFFFFFFFF` cannot wrap (XDR self-test case 11).

**D12. Paths.** A caller path is split on `/` **and** `\`, because the legacy separator is `\`
(`NFSClient.cs:816`, `NFSv3.cs:250`). Empty and `.` components are skipped. **`..` is refused**
(`E_UNSAFE_PATH`), so no user input can walk above the export root. The server's own `..`
entry is never followed, because entries named `..` are dropped (D6). Control bytes are
refused. Each component is re-encoded into the server charset for `LOOKUP`. If it cannot be
represented → `E_CHARSET`. The walk is one `LOOKUP` per component, plus a `GETATTR` when
LOOKUP returned no attributes.

**D13. `UseCache`.** When on, the resolved (path → handle, attrs) pairs are cached per mount,
up to 4,096 of them, and the cache is cleared on mount, disconnect and `STALE`. The legacy v3
code ignored the flag (only v4.1 used it, `NFSv4.1.cs:87`).

**D14. Browse model for the adapters (sprch + #26).** The legacy root is the **export list**
(`NFS.cs:145-153`, `item == null` → `GetExportedDevices`). Each export is a folder that is
mounted on open (`NFS.cs:156-157`). A virtual path therefore names both parts:
`"<export>//<relpath>"`. Export paths are absolute and never contain `//`, so the first `//`
is the boundary. Root `""`/`"/"` lists exports, named with `/` shown as U+2215 so the #26
"no `/` in a name" rule holds. If the settings carry `Path`, root is that export's top
directory, and any vpath for another export is `NOTFOUND`.

**D15. The locator** (#26 decision #1): `nfs://host[:nfsport]/export/rel?mountport=&nfsport=&uid=&gid=`.
This is the libnfs URL syntax, with each segment percent-encoded and query keys only when
they are non-default. NFS is **not** `SPFFA_CAP_RANGE`, because the locator is for the NFS
opener (this DLL's `open`/`read_at`), not for HTTP `sprs`. `stream_url` returns
`{"url":<locator>,"size","mtime_ms"}`. It carries no secret: AUTH_SYS has none.

**D16. sprch handler** `runtime_type = "NFS"`, caps `VALIDATE|LIST|STREAM` (0x23):
- `validate` = `TestNFSConnection` (`Handler:41-76`). Connect, then `EXPORT`. If the list is
  non-empty the delta is `{"RuntimeType":"NFS"}` plus `"ID":<new GUID>` when `ID` is empty. If
  it is empty → `E_NOTFOUND` (the legacy code showed nothing, i.e. silently failed).
- `list` is D14. `download` → `E_NOTSUPPORTED` (the legacy code returned null).
- ⚠️ **Legacy defect:** `CreateRootFolder` (`Handler:11-24`) builds the folder **and then
  returns `null`**, so the handler never produced a browsable root. The UI only worked because
  other call sites built `NFSBridgeFile` directly. Also `nfs.IsConnected` NREs when
  `TryGetNFSClient` returns null (`Handler:16-17`).
- Every per-call session is opened, used and UMNTed inside the call (stateless).

**D17. #26 backend** `id = "nfs"`, `CAP_STAT`. The listing is fetched once per path and paged
from a cache with a numeric cursor. The cursor is re-validated against the path, and a
different path re-lists. `stat` of an export root works, and the root itself is the synthetic
folder `"/"`. `locator` refuses folders.

**D18. The hidden rule (kept exactly, and made explicit).** `Accessor:107-109` hides only
**folders** named `$*`, `.*` or `@*` (`@eaDir`, `#recycle`-style Synology/QNAP dirs, `.git`).
For files, `Accessor:85` calls `IsHidden()`, which is **always `false`** for NFS (`NFS.cs:135`).
So `.DS_Store` or `@x.txt` files **were shown**. Mode 1 (the default) is exactly that. Mode 2
also hides files (row 27 browse policy may prefer it). Mode 0 shows everything. Hidden entries
are removed from `spnfsc_list` and counted (`list_hidden_count`). `stat_json` reports
`"hidden"`.

## 3. Error taxonomy (`include/spnfsc.h`)

| Code | From |
|---|---|
| `E_NETWORK` -1 | refused, reset, timeout, DNS, transport non-200 |
| `E_PROTOCOL` -2 | XID mismatch, malformed or truncated reply, `GARBAGE_ARGS`, `BAD_COOKIE`, `INVAL`, READ count lies |
| `E_AUTH` -3 | RPC `AUTH_ERROR` other than TOOWEAK, transport 401/403 |
| `E_ACCESS` -4 | `NFS3ERR_PERM/ACCES`, `MNT3ERR_PERM/ACCES` |
| `E_NOENT` -5 | `NFS3ERR_NOENT/NXIO/NODEV`, `MNT3ERR_NOENT/NODEV`, unknown vpath |
| `E_STALE` -6 | `NFS3ERR_STALE/BADHANDLE` after one re-resolve |
| `E_NOTDIR` -7 / `E_ISDIR` -8 | the obvious |
| `E_UNSUPPORTED` -9 | NFS version setting, `PROG_MISMATCH`, `PROC_UNAVAIL`, v4-only server |
| `E_INVALID_ARG` -10 | bad host / handle / offset / settings |
| `E_NOT_CONNECTED` -11 | no connect or no mount |
| `E_PRIVILEGE` -12 | D8 |
| `E_LIMIT` -13 | D11 |
| `E_OOM` -14 | |
| `E_SERVER` -15 | `NFS3ERR_IO/SERVERFAULT`, `JUKEBOX` exhausted, `SYSTEM_ERR` |
| `E_NOPROG` -16 | `PROG_UNAVAIL`, MOUNT not registered |
| `E_UNSAFE_PATH` -17 | `..` or a control byte in a caller path |
| `E_CHARSET` -18 | unknown charset, name not representable |

**A network failure is never an empty folder.** Every listing path returns an error code or
the full listing. The legacy `ListFilesAsync` (`NFS.cs:140-168`) never called `SetResult` on
an empty list or an exception, so the task **hung forever**. The sprch mapping: ACCESS,
PRIVILEGE and AUTH → `E_AUTH`; NOENT, NOTDIR, ISDIR and UNSAFE → `E_NOTFOUND`; NETWORK, SERVER,
STALE and NOPROG → `E_NETWORK`; PROTOCOL and LIMIT → `E_PROTOCOL`; settings problems →
`E_CONFIG`.

## 4. Charsets

The decode is total: invalid input becomes U+FFFD, and NUL becomes U+FFFD, so a name is always
valid UTF-8 without a NUL. GBK (cp936, plus 0x80 → €) and Big5 (cp950) use generated 126×191
tables (`tools/gen_charset.py` from Python's codecs, the same WHATWG-compatible mappings that
.NET `CodePagesEncodingProvider` uses for 936/950). Latin-1 is identity. `ascii` maps
bytes ≥ 0x80 to `?`, like .NET `ASCIIEncoding`. Encode (for `LOOKUP`) is the reverse.
Oracle: GBK and Big5 raw-byte names on a real server decode, and `LOOKUP`+`READ` round-trips.

⚠️ **Legacy default was ASCII** (`Connectors:55`, and `NFSClient.cs:176,181`). Every
non-ASCII name on a UTF-8 NAS arrived as `????.mkv`, and a second file with the same length
and position collided. We default to UTF-8.

## 5. Threading

There is one global session, not thread-safe, and the fleet style is that a shell serialises
calls. The sprch handler and the spffa backend use their own sessions and never touch the
global one.

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

- **Q1.** Should the default hidden mode become 2 (hide `.DS_Store`)? That is row 27's call.
  We keep legacy 1.
- **Q2.** NFS over RDMA, `nconnect` (several TCP connections) and `rsize` > 1 MiB are not done.
  Pipelining on one connection already saturates loopback (§12).
- **Q3.** An IPv6 literal host works in the socket layer. The locator brackets it. It has not
  been tested against a v6 server.
- **Q4.** A symlink is listed as `kind:"symlink"`, `folder:false`, and is never followed. The
  player cannot open a symlinked movie. The legacy code did the same (`NFSClientNFSItemTypes`
  NFLNK treated as a file, then `READ` fails with `INVAL`). Following links inside the export
  is a product decision.

## 11. The fake server (`spnfsc_use_fake`, `spnfsc_io_fake`)

The tree comes from JSON (`src/spnfsc_fake.c` header): exports, groups, and nodes with
`children`, `size`, `mtime`, `text`, `symlink` and `deny`. `"generate":N` makes N files, and a
`"hex:…"` name gives raw bytes. File bytes are deterministic: `(fileid*31 + off*7 + off>>8) & 0xFF`.
Faults are set with `spnfsc_fake_set_fault(name, n)`: `noplus`, `jukebox` (n times), `stale`
(n times), `tooweak`, `drop` (n replies), `garbage` (n), `page` (entries per page, default 50),
`mount_deny`, `bad_count` (READ data > asked), `huge_len` (a 2 GB export string), `pmap_dead`,
`nfs_v4_only` and `reset_counts`. It implements only read procedures and counts every call per
(program, proc).

## 12. Measured (see README / the report for the full tables)

Loopback kernel nfsd (Ubuntu 22.04, 6.8 kernel) and nfs-ganesha 3.5 (VFS FSAL), exporting a
generated tree (`tools/oracle/make_tree.py`):
20,000-entry directory, CJK/emoji/combining/RTL/`#%+` names, raw GBK + Big5 names, a 5 GiB
sparse file, a 1 GiB data file, file/dir/dangling/absolute symlinks, `@eaDir`/`.hidden`/
`$RECYCLE.BIN`, an empty dir and a 0-byte file.
`tools/oracle/oracle.py` compares against `showmount -e`, `rpcinfo -p`, `lstat` (name, kind, size,
mtime ms, fileid), `sha256sum`, libnfs `nfs-cat`, and random-offset reads vs the local bytes.
