# SPEC: scorpiox-scorpioplayer-dlna-upnp-media-server (`spdms_`)

A pure C99, zero-dependency **DLNA Digital Media Server** for SCORPIO PLAYER 2027. It shares local
folders and single files so TVs, consoles, VLC and other control points can browse and stream them
(with byte seeking). Written in C99 with no libupnp, gupnp or libxml2. JSON output uses the vendored
yyjson (fleet rule 14).

## 0. Spec sources

**No C# spec exists for DLNA.** TPlayer used the OS for both halves:

| Legacy | What it did | file:line (tplayer `71ca80f` / bosxixi.toolkit `0a8411d`) |
|---|---|---|
| Browse DMS | `KnownFolders.MediaServerDevices.GetItemsAsync()`, retried once when empty | `TPlayer/ContentDialogs/MediaServerDevicesDialog.xaml.cs:88-92` |
| Favourites | DMS folders become `PlayListFolder(folder, ContentSource.DLNA)` | `TPlayer/Views/Pane.cs:661-680`, `:699` |
| Cast | `CastingDevicePicker` → `GetAsCastingSource()` | `TPlayer/Features/Casting.cs:38-89` |
| DLNA tree UI | 147 of 204 lines commented out, last touched `8f93597a` 2019-03-20 "DLNA normalized" | `TPlayer/Features/DLNA.cs` |
| Own server | proprietary TCP protocol, not DLNA | `bosxixi.ScorpioPlayer.Core/MediaServer/Server.cs` (411 LOC, last `d25b675` 2020-09-21) |

This engine is therefore specced from the standards:

- UPnP Device Architecture 1.1 (UDA): SSDP, description, SOAP control, GENA eventing
- UPnP AV `MediaServer:1`, `ContentDirectory:1` (CDS), `ConnectionManager:1` (CM)
- DLNA guidelines: `protocolInfo` 4th field, `contentFeatures.dlna.org`, `transferMode.dlna.org`
- Oracles: `gssdp-discover`, `gupnp-av-cp`, `async_upnp_client`, VLC, `minidlna` 1.3.0, `curl`, `xmllint`

### What the legacy server teaches (behaviour only, wire format NOT ported)

| # | Legacy behaviour | file:line | Decision here |
|---|---|---|---|
| L1 | `OpenFile` with `FullName != null` opens **any path the client sends** (`new FileInfo(sf.FullName).OpenRead()`) | `Server.cs:256-263` | **P0 in legacy: unauthenticated arbitrary file read.** Here a URL carries only an opaque object ID (D5, D14) |
| L2 | `SubFolders` / `OpenFolder` list **any directory the client names** (`Directory.GetDirectories(str)`) | `Server.cs:351-369` | Same class of bug, directory disclosure. Here browse only walks shared roots |
| L3 | One `BasePath`; subfolders one level deep (`Folders` → `OpenFolder`) | `Server.cs:119,340-380` | Many roots, folder or file, recursive (D6) |
| L4 | Sidecar subtitles = every file whose name `Contains(stem)` with a subtitle extension | `Server.cs:302,311,316` | Too loose (`a.mkv` matches `aa.srt`). Here: same stem, then `.` or end (D10) |
| L5 | Content type: audio ext → `"audio"`, else `"video"` | `Extension.cs:431-443` | MIME per extension, 3 classes + subtitle (D9) |
| L6 | Extension lists `PictureTypes`, `AudioTypes`, `VideoTypes`, `SubtitleTypes` | `Extension.cs:444-530` | Used as the seed for the MIME table (D9) |
| L7 | `HasSubFolder` via `EnumerateDirectories().Any()`, exceptions → folder dropped | `Server.cs:17-34` | `childCount` computed from the index; unreadable dirs skipped, not fatal |
| L8 | Read loop: `Math.Min(Length - Position, count)` chunks | `Server.cs:181,211` | HTTP Range with 64-bit sizes and 64 KiB chunks (D12) |
| L9 | Binds `TcpListener(LocalAddr, Port)` with a caller-given address | `Server.cs:85` | Same: caller picks one interface; `0.0.0.0` refused (D1) |

## 1. Scope

In: SSDP (alive, byebye, M-SEARCH reply), device + two SCPD descriptions, CDS:1 `Browse` /
`GetSearchCapabilities` / `GetSortCapabilities` / `GetSystemUpdateID`, CM:1 `GetProtocolInfo` /
`GetCurrentConnectionIDs` / `GetCurrentConnectionInfo`, GENA eventing for both services, HTTP
GET/HEAD media with byte ranges, runtime share/unshare.

Out: transcoding, thumbnails (`upnp:albumArtURI`), CDS `Search`, DTCP, AV v2+, IPv6 SSDP, time-based
seek (`TimeSeekRange.dlna.org` → 406), any write action, `X_MS_MediaReceiverRegistrar`.

## 2. Decisions

**D1. Bind to one interface, chosen by the caller.** `spdms_start(bind_ip, …)` requires an IPv4
literal. `0.0.0.0`, `255.255.255.255`, multicast addresses and hostnames return `SPDMS_E_ARG`. The
HTTP listener binds `bind_ip:http_port`, where port 0 means an ephemeral port. `LOCATION` uses
`bind_ip` and the real port, so it is always reachable on that interface (the LAN quirk where
Sony's reply IP ≠ its LOCATION host is why the server must never advertise a wildcard). (L9)

**D2. SSDP socket.** The group and port default to `239.255.255.250:1900`; `spdms_config("ssdp_group"|"ssdp_port")`
changes them (tests use a private group on a random port). Linux binds the group address with
`SO_REUSEADDR`+`SO_REUSEPORT` and `IP_MULTICAST_ALL=0`, then joins the group on `bind_ip` only.
Windows binds `bind_ip:port` and joins on `bind_ip`. Replies and NOTIFYs go out from a second socket
bound to `bind_ip:0`, with `IP_MULTICAST_IF=bind_ip`, TTL 2 (UDA 1.1 default) and loop on.
`ssdp_disable=1` runs HTTP only.

**D3. M-SEARCH.** It must be `M-SEARCH * HTTP/1.1` with `MAN: "ssdp:discover"` (quotes required,
UDA 1.1 §1.3.2). Multicast searches need an `MX`: missing or non-numeric → ignored, `MX > 5` clamped to 5
(UDA), `MX < 1` → 1. Unicast M-SEARCH (UDA 1.1 §1.3.3, sent to our address) is **not** answered: the receive socket is bound to the group so it cannot see unicast; noted as Q6. Responses
are delayed by a random `0..MX*1000` ms and held in a bounded 64-entry queue; overflow is dropped.
We answer **only our own types** (the Hue bridge answers every ST, which is a real false positive
on our LAN):

| ST | responses |
|---|---|
| `ssdp:all` | 5: `upnp:rootdevice`, `uuid:…`, `device:MediaServer:1`, `service:ContentDirectory:1`, `service:ConnectionManager:1` |
| `upnp:rootdevice` | 1 |
| `uuid:<ours>` | 1 (USN = the uuid alone) |
| `urn:schemas-upnp-org:device:MediaServer:1` / `service:ContentDirectory:1` / `service:ConnectionManager:1` | 1 each |
| anything else, including `MediaServer:2` and `MediaRenderer:1` | none |

The reply headers are `CACHE-CONTROL: max-age=N`, `DATE`, `EXT:`, `LOCATION`, `SERVER: <os>/<ver> UPnP/1.1 scorpiox-dms/1.0.0`,
`ST`, `USN`, `BOOTID.UPNP.ORG` and `CONFIGID.UPNP.ORG: 1`.

**D4. NOTIFY.** On start, the server sends `ssdp:alive` for the 5 NTs twice, 100 ms apart (UDP is lossy). It
repeats them every `max-age/2` seconds, minus up to 10 % random jitter. `max-age` defaults to 1800 (config key `max_age`, 60..86400).
`spdms_stop()` sends `ssdp:byebye` for the 5 NTs, twice. `BOOTID.UPNP.ORG` is the start time in seconds.

**D5. Stable UUID.** The UUID is an RFC 4122 v5 UUID (SHA-1, URL namespace) of
`"scorpiox-dms:" + friendly_name + "@" + hostname`. Restarts keep it, and two servers on one host get
distinct UUIDs only if their names differ. Config key `uuid` overrides it (tests use this).

**D6. Content roots.** A root is a folder or a single file. The path is canonicalised (`realpath` /
`GetFullPathNameW`) and must exist:
- **folder root** → a top-level `container` under `0`, titled with the folder's basename, walked recursively
- **file root** → a top-level `item` directly under `0`

Top-level order = the order roots were added (predictable for users; each folder's own children are
natural-sorted). Adding the same canonical path twice is a no-op that returns the existing index.
Overlapping roots (a file inside an already-shared folder, or a folder in a folder) are allowed and
get distinct IDs (D7).

**D7. Object ID scheme.** `0` is the root. Every other ID is 16 lower-case hex digits: FNV-1a 64 over the
**root-qualified relative path** `K = kind ":" root_canonical_path "|" relpath`, where kind is `D` (folder root) or `F` (file root)
and relpath uses `/` separators (`""` for the root itself). So IDs are stable across restarts and rescans, independent
of inode, walk order and index, and a file shared both alone and inside a shared folder has two IDs.
`spdms_object_id_for_path(K)` is the pure hash. On a (vanishingly unlikely) collision inside one index, the later
entry is renamed to FNV-1a of `K "#1"`, `#2`, and so on (deterministic given the same tree).

**D8. Walk rules.** Names starting with `.` are skipped (hidden files and dot-dirs); on Windows,
`FILE_ATTRIBUTE_HIDDEN|SYSTEM` entries are skipped too. Symlinks are followed only when their target's canonical path is still
inside the root's canonical path (no escape); directories are tracked by (dev, ino) to break loops. Max depth 32, and
max 200,000 entries per root (the rest are dropped with a warning in `spdms_last_error`). Only video, audio and image files
become items; subtitles attach to videos (D10); every other file is ignored. Empty folders
are still listed (a TV can show them). Children are sorted containers first, then items, each
in **natural order**: case-insensitive, with digit runs compared numerically (`ep2` < `ep10`).

**D9. MIME table** (built into the C, no libmagic), seeded from `Extension.cs:444-530` (L6) plus DLNA-standard types:

| class | extensions → MIME |
|---|---|
| `object.item.videoItem` | mp4 m4v `video/mp4`, mkv `video/x-matroska`, avi `video/x-msvideo`, webm `video/webm`, mov `video/quicktime`, ts m2ts mts `video/mp2t`, mpg mpeg vob `video/mpeg`, flv f4v `video/x-flv`, wmv `video/x-ms-wmv`, ogv `video/ogg`, 3gp `video/3gpp`, rm rmvb `application/vnd.rn-realmedia` |
| `object.item.audioItem.musicTrack` | mp3 `audio/mpeg`, m4a `audio/mp4`, aac `audio/aac`, flac `audio/flac`, wav `audio/wav`, wma `audio/x-ms-wma`, ogg oga `audio/ogg`, opus `audio/ogg` |
| `object.item.imageItem.photo` | jpg jpeg `image/jpeg`, png `image/png`, gif `image/gif`, bmp `image/bmp`, heic heif `image/heic`, webp `image/webp` |
| subtitle (sidecar only) | srt `text/srt`, ass ssa `text/x-ass`, vtt `text/vtt`, sub `text/plain`, smi `application/smil` |

The legacy `VideoTypes` includes `.m3u` (a playlist, not a video): **dropped deliberately**.

**D10. Sidecar subtitles.** For a video `stem.ext`, every sibling `stem.srt`, `stem.<tag>.srt`, and
the same for `.ass`/`.ssa`/`.vtt`/`.sub`/`.smi`, becomes (a) a second `<res protocolInfo="http-get:*:text/srt:*">` and
(b) `<sec:CaptionInfoEx sec:type="srt">URL</sec:CaptionInfoEx>` (Samsung, namespace
`http://www.sec.co.kr/`). Order: `.srt` files first, then the others in natural order; only the first becomes the `sec:` element, because Samsung reads only one and renders SRT. The
HTTP response for the video carries `CaptionInfo.sec: URL` when the request has
`getCaptionInfo.sec: 1`. The match is stem then `.` or end, case-insensitive (L4 fixed). Max 8 subtitles per video.

**D11. protocolInfo / DLNA headers.** `http-get:*:<mime>:<4th>`, where 4th is
`DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=<flags>`. `OP=01` means byte seek yes, time seek no. The flags
are `01700000…` (DLNA v1.5 | stalling | background | streaming) for AV and `00F00000…` (v1.5 | stalling | background | interactive)
for images, as `%08X` followed by 24 zeros. **No `DLNA.ORG_PN`**: a profile name claims a codec/resolution we have not probed,
and a wrong PN makes strict TVs refuse the file, while an absent PN makes them try. The HTTP media response echoes
`transferMode.dlna.org` from the request when it is `Streaming`, `Interactive` or `Background`, otherwise
`Streaming` for AV and `Interactive` for images, and always sends `contentFeatures.dlna.org: <4th>`.

**D12. HTTP media.** URLs are `/m/<id>.<ext>` for the item and `/s/<id>/<n>.<ext>` for subtitle n (the extension is
decorative; some TVs sniff it). `GET` and `HEAD` are served; any other method → 405. Range handling, via `spdms_parse_range(hdr, size, &a, &b)`:

| header | result |
|---|---|
| absent | 200, full body |
| `bytes=a-b` (a ≤ b, a < size) | 206, `b` clamped to `size-1` |
| `bytes=a-` (a < size) | 206, `a..size-1` |
| `bytes=-n` (n > 0) | 206, last `min(n,size)` bytes |
| `a ≥ size`, `-0`, or anything on a 0-byte file | **416** with `Content-Range: bytes */size` |
| malformed, non-`bytes` unit, or multi-range `a-b,c-d` | **ignored → 200 full** (RFC 9110 permits ignoring Range) |

The parser returns 0 (satisfiable), 416, or -1 (ignore). Sizes are `long long`, so 4 GiB+ files work.
Every response sends `Accept-Ranges: bytes`, `Content-Length`, `Content-Type` and the DLNA headers.
`TimeSeekRange.dlna.org` → 406. The body goes out in 64 KiB `pread` chunks.

**D13. HTTP server limits.** Request head ≤ 16 KiB; request body ≤ 64 KiB (`Content-Length`
only; `Transfer-Encoding: chunked` bodies → 411); keep-alive by HTTP/1.1 rules (`Connection: close`
honoured; HTTP/1.0 closes unless it sends `keep-alive`); 30 s idle timeout; 1,000 requests per connection.

**D14. Path traversal is structurally impossible.** A URL path is split into fixed route + hex ID;
the ID must be exactly 16 `[0-9a-f]` (anything else, including `..`, `%2e%2e`, `/`, `\`, NUL, absolute paths and
over-long IDs → 404). The ID is looked up in the index and the file path comes only from the index. At
open time the canonical path is re-resolved and must still sit under the root's canonical path (a symlink swapped
in after the walk → 404). A libFuzzer target and a unit fuzz loop over the router prove it (§5).

**D15. SOAP reader (bounded, no DTD).** A hand-written tokenizer, not a general XML parser:
body ≤ 64 KiB, depth ≤ 32, ≤ 32 arguments, each ≤ 8 KiB. Any `<!DOCTYPE`, `<!ENTITY` or `<!` other than
`<!--`/`<![CDATA[` → reject. Entity references: only the 5 predefined + `&#N;`/`&#xN;` (valid code points only);
anything else, e.g. `&lol9;` → reject. So XXE and billion-laughs are refused before any expansion. The action
element is the first child of `s:Body`; its namespace URI must be the service type and must match the `SOAPACTION` header
(`"urn:…:service:ContentDirectory:1#Browse"`, quotes optional). A reject is a SOAP fault, 402 Invalid Args, or HTTP 400 for a non-XML body.

**D16. Actions and errors** (UPnPError in a SOAP fault, HTTP 500):

| code | when |
|---|---|
| 401 Invalid Action | unknown action, `Search`, and every write action: `CreateObject`, `DestroyObject`, `UpdateObject`, `ImportResource`, `ExportResource`, `DeleteResource`, `CreateReference`, `StopTransferResource`, `GetTransferProgress`, CM `PrepareForConnection`/`ConnectionComplete` |
| 402 Invalid Args | missing required argument, non-numeric `StartingIndex`/`RequestedCount`, bad `BrowseFlag`, XML reject (D15) |
| 701 No such object | unknown `ObjectID` |
| 706 Invalid connection reference | `GetCurrentConnectionInfo` with an ID other than `0` |
| 720 Cannot process the request | `BrowseDirectChildren` on an item |

`Browse`: `BrowseMetadata` returns the object itself (`StartingIndex` must be 0, else 402).
`BrowseDirectChildren` returns children `[StartingIndex, StartingIndex+RequestedCount)`, where `RequestedCount 0` means all (capped at 5,000 per call).
`TotalMatches` = child count, and `UpdateID` = the container's update ID (D18). `SortCriteria` is accepted and ignored
(we always natural-sort, and `GetSortCapabilities` returns `""`). `Filter`: `*` = everything; otherwise
`res` / `res@size` / `sec:CaptionInfoEx` / `@childCount` tokens control the optional properties; `dc:title`,
`upnp:class`, `@id`, `@parentID` and `@restricted` are always present (required by CDS).
`GetSearchCapabilities` and `GetSortCapabilities` → `""`. `GetSystemUpdateID` → `Id`.
CM: `GetProtocolInfo` → `Source` = the distinct `protocolInfo` strings from the MIME table, `Sink` = `""`.
`GetCurrentConnectionIDs` → `0`. `GetCurrentConnectionInfo(0)` → `RcsID -1, AVTransportID -1,
ProtocolInfo "", PeerConnectionManager "", PeerConnectionID -1, Direction Output, Status OK`.

**D17. DIDL-Lite.** The root element declares `xmlns`, `dc`, `upnp`, `dlna` and `sec`. For a container:
`<container id parentID restricted="1" searchable="0" childCount="N">` with `dc:title` and
`upnp:class object.container.storageFolder`. For an item: `<item id parentID restricted="1">`, then `dc:title`
(the file name minus its extension), `upnp:class`, `dc:date` (mtime, ISO 8601 UTC), and `<res protocolInfo size>URL</res>`, followed by
subtitle `res` and `sec:CaptionInfoEx`. `duration` is **not emitted**: no demuxer is linked, and a wrong duration breaks
seek bars (see the report's #26/probe note). The XML is escaped `& < > " '`, and control chars other than tab/LF/CR are dropped.
The `Result` is escaped once more inside SOAP.

**D18. Update IDs.** `SystemUpdateID` starts at 1 and is incremented by every add, remove and effective rescan. Each container
carries an update ID. A structural change sets the changed container's update ID to the new SystemUpdateID and
appends `id,updateid` to the pending `ContainerUpdateIDs`. Add/remove change `0`. A rescan compares
each container's child signature (FNV over sorted child IDs + sizes + mtimes) and bumps only the containers that
changed (plus `0` if a file root changed); a rescan with no change bumps nothing.

**D19. Eventing (GENA).** `SUBSCRIBE` with `CALLBACK: <http://a.b.c.d:port/path>` and `NT: upnp:event`
creates a subscription. The SID is `uuid:` + a random v4, and `TIMEOUT: Second-N` is honoured clamped to 60..3600, where `infinite` → 1800.
Renewal is `SUBSCRIBE` with `SID` and no `CALLBACK`/`NT`. `UNSUBSCRIBE` takes `SID`. Errors: SID together with CALLBACK/NT
→ 400; missing NT/CALLBACK, bad CALLBACK, or unknown SID → 412. Expiry is enforced by the event thread, and at most 64 subscribers are held (the 65th gets 503).
**CALLBACK must be an `http://` URL with an IPv4 literal host** (no DNS; nothing but a NOTIFY is ever sent there).
The initial NOTIFY (SEQ 0) goes out right after the 200: CDS sends `SystemUpdateID` +
`ContainerUpdateIDs` (empty), and CM sends `SourceProtocolInfo`, `SinkProtocolInfo` and `CurrentConnectionIDs`. On every
add/remove/rescan that bumps anything, each live CDS subscriber gets `SystemUpdateID` + the accumulated
`ContainerUpdateIDs`. This is **moderated to at most one NOTIFY per 200 ms** (config `event_moderation_ms`;
see Q1). SEQ increments and wraps 2³²-1 → 1. A subscriber whose NOTIFY fails 3 times in a row is dropped.

**D20. Remove during stream.** Each root has a refcount and a `removed` flag. A streaming worker holds
a reference and checks `removed` before every 64 KiB chunk. On removal, it stops at the chunk boundary, closes the
connection (the only honest signal mid-body) and its fd, then drops the ref. The last ref frees the root.
Later requests for its IDs → 404 because the ID has left the index. `spdms_remove_path` returns without waiting.

**D21. Thread model.** One accept thread, one SSDP thread (M-SEARCH + delayed replies + periodic
alive), one event thread (moderated NOTIFY + expiry), and a fixed pool of 16 HTTP workers fed by a 64-slot
connection queue. A full queue → `503` and close. One global mutex guards the content index,
subscriptions and counters; DIDL is rendered under the lock into a per-request buffer, and file I/O runs without it.
The API is a **process singleton** (like rows 32/34/36/48). The pure exports (`spdms_didl_for`, `spdms_mime_for`,
…) return static buffers: one call at a time, copy before the next.

**D22. No `scorpiox_io`.** This engine is an inbound server with raw sockets. It makes no HTTP-client
request except the GENA `NOTIFY` verb to subscriber callbacks, which `scorpiox_io` (GET/POST only)
cannot express. The "fake backend" for tests is a temp directory tree plus loopback-only sockets on a
private SSDP group/port. The `.console --test` never touches a LAN host.

## 3. Error taxonomy (C return codes)

| code | name | meaning |
|---|---|---|
| 0 | `SPDMS_OK` | |
| -1 | `SPDMS_E_ARG` | bad argument (NULL, `0.0.0.0`, bad IP, bad key) |
| -2 | `SPDMS_E_STATE` | already running / not running |
| -3 | `SPDMS_E_NET` | socket/bind/join failure (message has errno) |
| -4 | `SPDMS_E_NOENT` | path does not exist / not shared |
| -5 | `SPDMS_E_NOMEM` | allocation failed |
| -6 | `SPDMS_E_LIMIT` | too many roots (64) or entries |
| -7 | `SPDMS_E_TYPE` | path is neither a regular file nor a directory |

`spdms_last_error()` holds a human-readable message for the last failing call.

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

- **Q1. Moderation rate.** The task says "at most 1 per 200 ms, per CDS §2.5". Whether CDS:1's text says 0.2 s
  or 2 s (0.5 Hz) for `SystemUpdateID`/`ContainerUpdateIDs` is not confirmed here (the PDF is not
  vendored). 200 ms is the default, and `event_moderation_ms` makes it a one-line change.
- **Q2. `DLNA.ORG_PN`.** Omitted (D11). If a real TV refuses unprofiled MP4, then `AVC_MP4_*` for `.mp4` would
  need a probe. Which engine owns probing is open; see the report.
- **Q3. Windows Media Player / Xbox** need `X_MS_MediaReceiverRegistrar`. Out of scope; not tested.
- **Q4. `duration`.** Needs a demuxer. Out of scope for this engine (D17).
- **Q5. Multiple NICs.** One interface per server instance by design (D1). A future "all interfaces" mode would be
  one SSDP socket per NIC with a per-NIC LOCATION. Not built.
- **Q6. Unicast M-SEARCH.** Not answered (D3). No control point used in the oracles needs it; Windows' SSDP service
  does use it for refresh. Adding it means a second socket bound to `bind_ip:1900`.

## 5. Tests

- `make test`: unit tests for every pure export, the SOAP reader (XXE, billion-laughs, depth 33,
  64 KiB+1), the router fuzz loop (path traversal), and an in-process server test (HTTP, SOAP, SUBSCRIBE
  NOTIFY, add/remove, remove-during-stream) on 127.0.0.1 with a private SSDP group.
- `make asan`: the same under ASAN + UBSAN.
- `make fuzz`: libFuzzer on `spdms_parse_range`, the SOAP reader and the URL router.
- `make oracle`: gssdp-discover, async_upnp_client browse + subscribe, gupnp-av-cp (headless check), VLC
  play + seek, minidlna DIDL diff, curl range matrix incl. a 5 GiB sparse file, xmllint against UPnP XSDs.
