# SPEC: scorpiox-scorpioplayer-aspnet-directory-listing-client (RuntimeType `ASPNET`)

A read-only media source over a web server's directory index, behind `sprch_handler`.
Spec sources: `reference/scorpiox-scorpioplayer-aspnet-directory-listing-client/csharp-reference/`
(`ASPNETFolderFileAccesssor.cs`, `ASPNETRuntimeConfigHandler.cs`, the indexer slice) and the
real servers in `tools/oracle/` (ASP.NET Core 8 `UseDirectoryBrowser` in 6 cultures, nginx 1.24
`autoindex`, Apache 2.4.58 `mod_autoindex` in 3 layouts). "C#" means the reference; "we" means
this engine. Section 7 lists the legacy defects, measured by compiling the reference unmodified.

## 1. Wire subset

| Operation | Requests | Notes |
|---|---|---|
| `list(folder)` | 1 `GET <root>/<encoded folder>/` | redirects: section 3 |
| `validate` | 1 `GET <root>` + at most 1 `GET <first file>` with `Range: bytes=0-0` | never crawls |
| `stream_url` | none | pure URL construction (D9) |
| `stat` (export only) | 1 `GET <file>` with `Range: bytes=0-0` | needs the scorpiox_http extension |
| `download` | none | `SPRCH_E_NOTSUPPORTED` |

Request headers (extension path): `Accept: text/html,...`, `User-Agent: scorpiox-aspnet/1.0.0`,
`Range: bytes=0-0` on probes. No other method than GET. No writes of any kind.

## 2. Decisions

**D1. Dialect by markup, never by `Server:`.** `src/listing_parse.c` scans the page once for markers:

| Dialect | Markers | Rows |
|---|---|---|
| ASP.NET Core `HtmlDirectoryFormatter` | `<tr class="file">` / `<tr class="directory">`, or `<table id="index">` inside `<section id="main">` (an empty folder) | `td.name > a` text, `td.length`, `td.modified` |
| Apache `mod_autoindex` | a `?C=` sort link, an icon `alt` of `[DIR]` / `[PARENTDIR]` / `[ICO]` / `[   ]` / `Icon `, `<address>Apache`, or `<h1>Index of` + `<li><a> Parent Directory` | HTMLTable rows (columns from the `?C=N/M/S` header links or header text), FancyIndexing `<pre>` lines (columns in header-link order), or the plain `<ul>` |
| nginx `autoindex` | `<h1>Index of` + `<pre>` and no Apache marker | `<pre>` lines: `<a href>` + `date time size` |

A page with none of these is `SPRCH_E_PROTOCOL` ("not a directory index"), never an empty list.
Checked in that order (ASP.NET first). IIS "directory browsing" is not a dialect here (section 9).

**D2. Culture-free parsing.** The engine never reads the process locale (`test_listing` re-runs
under `de_DE`, `fr_FR`, `ja_JP`, `en_US` and `C` UTF-8).
- *Size*: a grouped integer. One separator kind per value from `,` `.` space U+00A0 U+202F
  U+2009 `'` U+2019 U+066C; first group 1-3 digits, last group exactly 3, middle groups 2-3
  (Indian `12,34,567`). `1.2K`, `1.5`, `1,23`, `1,234.5`, `-`, empty -> unknown (-1). Up to
  `LLONG_MAX`. ASP.NET writes `n0` in the server culture (`1,234` / `1.234` / `1 234` with
  U+202F); all read as 1234.
- *Date*: read by shape. Tokens: digit runs, English month names (`Sep`, `September`),
  AM/PM markers (`AM`, `pm`, `a.m.`, 午前/午後, 上午/下午, 오전/오후), an offset `+HH:MM` / `Z` /
  `UTC` / `GMT`, separators `/ . - : ,` and spaces (U+00A0, U+202F, U+2009). Any other letter ->
  unknown (never a guess). A 4-digit first number is the year (Y/M/D: ja, zh, ko, ISO, Apache).
  A 4-digit third number leaves d/M vs M/d to the page (D7). 2-digit years, impossible dates,
  years outside 1970..9999 and pre-epoch results -> -1. The offset is applied; without one the
  time is taken as UTC (nginx and Apache print server local time without a zone: section 9).

**D3. Transport: scorpiox_io v1 plus an optional scorpiox_http extension.** `sprch_handler`
receives only a `scorpiox_io *` (GET/POST, no headers, backend-followed redirects). With v1
alone the handler works but cannot see the final URL after a redirect, cannot send `Range`, and
cannot tell 206 from 200. So the engine looks up a bound `scorpiox_http` (the fleet proposal in
`include/scorpiox-http.h`, copied unmodified from the webdav-client repo, SPEC D1 there) for the
`scorpiox_io` it is given, keyed by `(http_get, ctx)` so copies of the struct still match.
Our libcurl and fake transports are pre-bound; `spaspnet_bind_http()` binds a platform backend
(Swift `URLSession`, WinHTTP). An unbound io (for example the conformance suite's wrapper) uses
the v1 path. What the v1 path costs, measured in `tools/oracle/results/redirects.md`:

| | scorpiox_http | scorpiox_io v1 |
|---|---|---|
| redirects | followed by the engine (D4) | followed by the backend (libcurl: <= 5) |
| base for hrefs and item URLs | the final URL | the requested URL (item URLs keep the old path / scheme; every later request redirects again) |
| absolute hrefs behind a path-changing redirect | resolved correctly | not children of the requested URL: skipped (an empty list; test_unit proves both) |
| `validate` range check, `stat` | yes | `unverified` / `SPRCH_E_NOTSUPPORTED` |

**D4. Redirects.** The extension path follows 301, 302, 303, 307, 308 with a `Location`, at most
5 hops (the 6th is `SPRCH_E_PROTOCOL` "more than 5 redirects"; libcurl's v1 face fails the same
input with "Maximum (5) redirects followed" -> `SPRCH_E_NETWORK`). `Location` is resolved per
RFC 3986 5.2 against the current URL, the fragment dropped; the target must be http(s);
https -> http is refused. A 3xx without `Location` is final (`SPRCH_E_PROTOCOL`). Loops end at
the hop limit. The final URL is the base for every relative href on the page.

**D5. Credentials.** The settings have no credential keys (`URL`, `ID` only). A URL with userinfo
(`https://user:pass@host/dl/`) works: userinfo is split off the base, sent by the transport
(extension: `username`/`password`, Basic or Digest; v1: embedded in the URL for the backend),
only to the original origin or its https upgrade; after a redirect to another origin it is
dropped. It never appears in list output, `result_json`, `last_error` or error JSON (transport
messages are scrubbed of the password and of a user name of >= 4 bytes). `stream_url` returns
the URL without userinfo plus `headers: {"Authorization": "Basic ..."}`.

**D6. validate writes a permanent same-host move back to `URL`.** When the root answered through
301/308 only, to the same host (or its https upgrade), and the URL carries no userinfo,
the delta carries `"URL": "<final directory URL>"`. The default server is exactly this case
(`http://fs.scorpioplayer.com/dl/` -> 308 -> `https://...`). After it, `stream_url` hands the
player https URLs (iOS ATS) and nothing redirects again. C# keeps the URL as typed (divergence).
A temporary redirect (302/307) or a move to another host is followed but never written back.

**D7. `DateOrder`.** A page whose numeric dates all have day <= 12 cannot tell d/M from M/d
(`<html lang="en">` is all ASP.NET says; en-US and en-GB differ). The page votes: a first number
> 12 or a `.` / `-` separator means d/M, a second number > 12 means M/d; a contradicting page
stays ambiguous. `validate` writes `"DateOrder": "dmy"|"mdy"` when the root page decides, and
`list` uses it only for pages that have no deciding date. Otherwise such dates are -1.

**D8. validate = one root GET + one ranged GET.** The root must parse as a listing (C#
`TestFileServerAsync`: any `.file` or `.directory`). Then the first file whose size is not 0 gets
`Range: bytes=0-0`; the probe reads at most 64 body bytes (a server that ignores Range and
starts a 4 GiB 200 is cut off). Verdicts in `result_json.range.verdict`: `verified` (206 +
`Content-Range: bytes 0-...`; `size` = its total), `ignored` (200: seeking will re-download from
byte 0), `failed` (416, 206 without a usable `Content-Range`, other status, transport error),
`unverified` (v1 transport), `no-file` (the root lists only folders; no crawl). The verdict never
fails validate: the source still lists and plays. The delta: `RuntimeType`, `ID` (a new v4 GUID
only when absent), `URL` (D6), `DateOrder` (D7). Unknown keys are never echoed.

**D9. stream_url is pure.** `url = <URL setting> + percent-encoded path segments`. No network
(the conformance suite's C7 skips it for that reason). A folder entry -> `SPRCH_E_NOTFOUND`;
an entry without `path` -> `SPRCH_E_CONFIG`.

**D10. Names.**
- ASP.NET: the anchor text, HTML-decoded, one trailing `/` removed for folders. The href is not
  used: `HtmlDirectoryFormatter` writes `href="./{HtmlEncode(name)}"`, which is not URL-encoded
  (`./My Film #1 (2019).mkv`, `./%41 literal.txt`), so resolving it is exactly legacy defect L2.
- nginx / Apache: the href, entity-decoded, resolved against the page URL, kept only if it is a
  direct child of the page's directory (same scheme and authority, parent path equal segment by
  segment after percent-decoding, no query, no fragment); the name is its percent-decoded last
  segment. The anchor text is not used: nginx cuts it at 50 columns (`...-charac..&gt;`).
- A name is refused (counted in `rejected`) when it is empty, `.`, `..`, contains `/` (`%2F`),
  a C0 byte or DEL (`%00`, `%0A`), is not valid UTF-8, is longer than 1024 bytes, or repeats an
  earlier name (the first wins). Navigation links (parent, sort columns, breadcrumbs, other hosts,
  `javascript:`) are `skipped`, not rejected.
- HTML references: `&amp; &lt; &gt; &quot; &apos; &nbsp;`, decimal and hex numeric; a UTF-16 pair
  written as two references is joined; a lone surrogate, NUL or > U+10FFFF rejects the name. Other
  named references stay literal (none of the three servers writes them).

**D11. Paths.** An item's `path` is `"/"`-joined decoded names relative to the root
(`/Movies/Sub Folder/inner.mkv`); `folder_id` takes the same form (leading and repeated `/`
ignored; `""` or `"/"` = root). `.` / `..` segments, control bytes and invalid UTF-8 ->
`SPRCH_E_NOTFOUND`. URLs are rebuilt from the path: each segment percent-encoded with
`scorpiox_percent_encode` (RFC 3986 unreserved kept), folders end with `/`. Paths therefore
survive an http -> https move and are what `list()` / `stream_url()` take back.

**D12. Sizes.** -1 = unknown: every folder, Apache sizes >= 973 B (`1.0K`, `5.0G`: rounded),
nginx `autoindex_exact_size off` sizes >= 10000 B (`1205K`), the Apache plain list. A real 0 is 0.
C# drops every file whose size is not > 0 from playback (`GetMediaFileItemsAsync`): we list it.

**D13. Errors are errors.** HTTP 401/403/407 -> `SPRCH_E_AUTH`; 404/410 -> `SPRCH_E_NOTFOUND`;
429 -> `SPRCH_E_RATE`; 408, 5xx, transport failure -> `SPRCH_E_NETWORK`; a 200 that is not a
listing, a page over 16 MiB, more than 100000 entries, an unfollowed 3xx, other statuses ->
`SPRCH_E_PROTOCOL`; bad settings -> `SPRCH_E_CONFIG`. No failure returns `SPRCH_OK` with an
empty list (C#: every exception -> `null` -> "no files").

**D14. Output.** `list`: `{"items":[{"name","path","folder","size","mtime_ms","url"}]}` in page
order (the server's sort; deterministic). `url` is the direct, range-readable URL built from the
final base. `result_json` (full, also after `E_BUFFER`) adds `op`, `code`, `folder`, `dialect`,
`variant`, `date_order`, `date_hinted`, `final_url` (redacted), `redirects` (-1 = unknown on v1),
`transport`, `count`, `rejected`, `skipped`, `index_of`. On error the out buffer gets `{"error","code"}` if it
fits. `E_BUFFER`: `out[0] = 0`, nothing written past `cap`, the caller retries.

**D16. The page must be the folder that was asked for.** All three dialects title the page
`Index of <decoded path>` (ASP.NET `/dl/Movies/Sub Folder/`, nginx the same, Apache without the
trailing `/`). For `list(folder)` with a non-empty folder, that path (trailing `/` removed) must
end with `/<folder path>`; otherwise `SPRCH_E_PROTOCOL` "the server answered with the listing of
another folder". This catches a lossy redirect: nginx `location /old/ { return 308 /dl/; }`
answers `/old/Movies/` with the root listing, which both C# and a naive client would show as the
content of `Movies`. The root is not checked (its server path is unknown), a page without such a
title is accepted (no evidence), a different prefix (a reverse-proxy mount) is accepted.

**D15. Threads.** Handler calls are stateless and may run concurrently. Global state: the
installed io, the binding table, the fake routes, `last_error` / `result_json` (each behind its
own lock; the getters return a per-getter copy valid until the next call of that getter).

## 3. State machine (one `list` / `validate` call)

```
settings --parse--> [config error] -> E_CONFIG
   |
   v
build URL (root + encoded folder + "/") --> fetch:
   extension:  GET --3xx+Location--> resolve, check (http(s), no downgrade, hop <= 5, creds origin) --> GET ...
               GET --other--> final (status, body <= 16 MiB, final URL)
   v1:         backend GET (follows itself) --> final (status, body), final URL := requested URL
   |
   transport failure -> E_NETWORK      redirect failure -> E_PROTOCOL
   v
status map (D13) --> non-2xx -> error
   |
   v
parse (D1, D2, D10) with page URL = final URL --> not a listing / limits -> E_PROTOCOL
   |
   v
list(folder != ""): "Index of" path ends with the folder? (D16) --> no -> E_PROTOCOL
   |
   v
list: items JSON          validate: range probe (D8) -> delta (RuntimeType, ID, URL?, DateOrder?)
```

## 4. Auth

None in the settings (C# has none). Userinfo in `URL` only (D5). No tokens, no cookies.

## 5. Parser (`src/listing_parse.{h,c}`) — vendorable as is

libc only, C99, no JSON, no sprch. Row 33 (SPFS client) copies the two files. Entry point
`spdlp_parse(html, len, page_url, limits, out)`; building blocks (`spdlp_parse_size`,
`spdlp_parse_date`, `spdlp_html_decode`, `spdlp_pct_decode`, `spdlp_resolve`,
`spdlp_child_name`, `spdlp_utf8_valid`) are public for tests and fuzzing. The tokenizer is a
bounded single pass: comments, doctype, `<script>` / `<style>` bodies skipped; attributes
quoted or bare; case-insensitive tags. Truncated pages (EOF inside a tag, a reference or a row)
parse without error: `test_listing` parses every prefix of a real page.

## 6. Limits

| Limit | Value | Past it |
|---|---|---|
| page body | 16 MiB | `SPRCH_E_PROTOCOL` "larger than 16 MiB" (the transfer is cut, never a short list) |
| entries per page | 100000 | `SPRCH_E_PROTOCOL` |
| href length | 8192 bytes | that row rejected |
| name length | 1024 bytes UTF-8 | that row rejected |
| metadata cell | 4096 bytes | truncated (a size or date that long is garbage anyway) |
| URL setting / built URL | 8192 bytes | `SPRCH_E_CONFIG` |
| redirects | 5 | `SPRCH_E_PROTOCOL` (extension) / backend error (v1) |
| range probe body | 64 bytes | transfer stopped |
| request timeout | 120 s (connect 15 s, stall 60 s) | `SPRCH_E_NETWORK` |

## 7. Legacy defects (the reference compiled unmodified, `tools/csharp-oracle`)

Measured against the loopback servers (`tools/oracle/results/legacy.md`). Priority is for a user.

| # | P | C# | Defect | Measured | Us |
|---|---|---|---|---|---|
| L1 | P0 | `ASPNETFolderFileAccesssor.cs:102` | `long.Parse(size, AllowThousands)` in the **device** culture; the server wrote it in **its** culture. Any mismatch throws, the catch returns `null`, `GetMediaFileItemsAsync` returns null: every file of the folder disappears while its sub-folders still show. | 14 of 24 server x client culture pairs lose every file (e.g. an en-US server read by a de-DE or fr-FR phone; a de-DE server read by anyone but de-DE). | D2 |
| L2 | P1 | `:101`, `:105-108` | The href (`./` + HtmlEncoded name, not URL-encoded) is resolved as a URL, then `Uri.UnescapeDataString`. `#` starts a fragment; `%41` becomes `A`. | In every working pair, `My Film #1 (2019).mkv` and `%41 literal.txt` stream the wrong URL (HTTP 404 through .NET `HttpClient`). | D10, D11 |
| L3 | P1 | whole class | Only the ASP.NET classes are read. | nginx and Apache (all 3 layouts): 0 files, 0 folders, no error. | D1 |
| L4 | P1 | `:92-95`, `:118-122` | Failures look like an empty folder. AngleSharp's loader swallows transport errors and HTTP errors; the `catch` turns the rest into `null`. | nothing listening, a 404 and a file URL each return `[]` files, `[]` folders, no error (`legacy.md`, last table) | D13 |
| L5 | P2 | `:109-112` | Only `&amp;` is decoded in names. | `100% & &lt;more&gt;.mp4` | D10 |
| L6 | P2 | `:60` | Files with `Size <= 0` never reach the player. | the 0-byte file is dropped | D12 |
| L7 | P3 | `ASPNETRuntimeConfigHandler.cs:222-226` | The default URL is only filled in under a debugger, and it is `http://` (308 on every request). | - | D6 |
| L8 | P3 | `ASPNETRuntimeConfigHandler.cs:197-208` | The connection test only counts `.file` / `.directory` rows: no range check, nginx / Apache "fail". | - | D8 |

## 8. Deliberate divergences from the reference

D1 (three dialects), D2 (culture-free), D4 (explicit redirect policy), D5 (userinfo handling),
D6 (URL rewrite), D7 (DateOrder), D8 (range probe), D10 (names from text / decoded href),
D12 (0-byte files listed, rounded sizes unknown), D13 (errors). The indexer's walk
(`DelegateMediaCategorizer.ASPNET.slice.cs:8-11`) maps to `list("")` then `list(path)` for each
folder item; `test_unit` walks the fake tree and `spaspnet walk` walks every oracle server.

## 9. Not covered

- IIS directory browsing (`<pre>` with `<A HREF="/abs/path">` and `&lt;dir&gt;`) and lighttpd,
  Caddy, Python `http.server` pages: no marker, so `SPRCH_E_PROTOCOL`. Adding one is a new
  extractor in `listing_parse.c`.
- nginx / Apache times are server local time with no zone on the page; we read them as UTC.
- A numeric d/M page with no deciding date and no `DateOrder` keeps `mtime_ms = -1`.
- Non-UTF-8 pages (Apache `Charset=ISO-8859-1` with Latin-1 file names): such names are rejected
  (counted), not transcoded.
- The live `fs.scorpioplayer.com` was unreachable from the build sandbox (egress proxy 403);
  `tools/oracle/live.sh` is the probe to run from an allowed network.
