# SPEC: scorpiox-scorpioplayer-webdav-client (pure C99 WebDAV client + `sprch` handler `WebDAV`)

Spec source: `reference/scorpiox-scorpioplayer-webdav-client/csharp-reference/` (a fork of the
open-source `WebDAVClient` library, plus the SP2025 consumers). `file:line` below refers to
those files. That library is vendored code, so it is a *weaker* spec (tracker rule): we keep
what the player needed and let real servers (`rclone`, `cadaver`, Apache, nginx, dufs,
Nextcloud) decide what is correct. Measured results are in section 8. Findings are in section 7.

## 1. Headline: D1, the transport extension (`scorpiox-http.h`, proposed)

`scorpiox_io` (`include/scorpiox-io.h`, unmodified) has `http_get` and `http_post`, both
returning a NUL-terminated body. WebDAV needs five things it cannot express:

| Need | Why | `scorpiox_io` today |
|---|---|---|
| any method | `PROPFIND`, `MKCOL`, `MOVE`, `COPY`, `DELETE`, `PUT` | GET / POST only |
| request headers | `Depth`, `Destination`, `Overwrite`, `Range`, `translate`, `Content-Range` | none |
| binary bodies with a length | a video byte range is not a C string (NUL bytes) | `char *` + strlen |
| streaming, bounded reads | a 40 GB `Download` must never sit in memory | whole body malloc'd |
| auth | `NetworkCredential` (Basic or Digest, `Client.cs:118-122`) | none |
| response headers | `Content-Range` (did the server honour `Range`?) | none |

**D1. Decision: a separate, versioned vtable `scorpiox_http` in a new header
`include/scorpiox-http.h`. It is not a patch to `scorpiox-io.h`.** One entry point:

```c
int (*request)(void *ctx, const scorpiox_http_request *rq, long *http_code, char **out_err);
```

`rq` carries `struct_size`, method, URL, header lines, a body pointer + length, and
username / password. The backend negotiates Basic or Digest after a 401 challenge. It also
carries a timeout and two streaming callbacks: `on_header(name, value)` and
`on_body(data, n)`. `on_body` may return non-zero to stop the transfer. That is how a range
read stays bounded and `download_to_file` streams to disk. The backend never follows
redirects, so credentials never leave the origin (D12).

Why this and not the alternatives:

1. *Appending `http_request` to `scorpiox_io`*: `scorpiox_io` has no `struct_size`. A library
   built against the longer struct would read past the end of every caller's old struct:
   silent memory corruption across the fleet. Rejected.
2. *A WebDAV-only vtable in this repo*: every future HTTP engine (S3, OneDrive, Jellyfin
   range reads, the remote-seek stream) needs the same five things. A per-engine vtable means
   N backends × M platforms. Rejected.
3. *A new fleet header*: one libcurl implementation, one `URLSession` implementation, one
   WinHTTP implementation, shared by every engine. `struct_size` on both structs lets the
   header grow append-only. **Recommended.**

How `sprch` reaches it without changing `sprch.h`: `sprch_handler` entry points receive a
`const scorpiox_io *`. The engine keeps a small binding table
(`spwd_bind_http(io, http)`, D2): the `scorpiox_io` pointer is the key and the extension is
the value. Our libcurl and fake backends are pre-bound. Given an `io` with no binding, every
entry point returns `SPRCH_E_NOTSUPPORTED` with an explicit message. It never falls back to a
private transport, because `scorpiox_io` stays the only transport (iOS rule). **Proposal for
sprch v2:** add `const scorpiox_http *http` to the registry's call context, or define
`scorpiox_io_v2 { struct_size; ...; request; }`. Then the binding table goes away.

The header in this repo is a *proposal copy*. It lives in `include/scorpiox-http.h` and
should move to the fleet's `scorpiox-io` owner. `scorpiox-io.h` and `sprch.h` are
byte-identical to `reference/.../headers/`.

## 2. Decisions

Numbered, with the C# they come from. "C#" means the reference; "we" means this engine.

**D2. Backends.** `spwd_use_curl()` (libcurl, default), `spwd_use_fake()` (canned
responses, offline, deterministic; tests and `.console --test`), and `spwd_set_http()` /
`spwd_bind_http()` for any external implementation (Swift `URLSession` on iOS).
`spwd_set_io(io)` accepts any `scorpiox_io`, but it can only be *used* when it is bound to an
extension (D1). Otherwise every request fails with `SPWD_ERR_NO_IO`.

**D3. Paths are decoded, relative to the base path.** Every `path` argument is a
human path (`/Movies/My #1 film.mkv`), never a URL and never pre-encoded. The engine
percent-encodes each segment with RFC 3986 *unreserved* kept and everything else encoded
(`scorpiox_percent_encode`). `spwd_item_path(i)` returns the same form, so a listed item's
path can be passed straight back. C# instead mixes forms: it passes the server's encoded
`href` back into `List(item.Href)` (`WebDAVFolderFileAccesssor.cs:90`) and a decoded
`BasePath` elsewhere. That mix causes the double-base-path bug C5.

**D4. No base-path discovery round trip.** C# `GetServerUrl` sends a `PROPFIND` of the base
on first use and adopts the returned `href` as `_encodedBasePath` (`Client.cs:698-704`).
It is cached per `Client`, but SP2025 builds a new `Client` for every validate, every root
listing and every playback (`WebDAVRuntimeConfigHandler.cs:22,45,124`). So each of those
pays one extra request. Within one `List` it is cached: 10,000 entries cost one discovery,
not 10,000. We compare **decoded** paths (D6), so the server's encoding choice does not
matter and the extra request is gone. `list` is exactly one request.

**D5. Server and base path.** `spwd_set_server("scheme://host[:port]")`: http/https only,
no userinfo, no query / fragment. A trailing path is moved into the base path
(C#: `Server.TrimEnd('/')`, `Client.cs:63`). The base path is normalised to `/a/b/`
(C#: `Client.cs:76-80`). The port is explicit or the scheme default (C# `Port` is `int?` but
`(int)Port` throws on null, `Client.cs:700`).

**D6. `href` resolution.** A full `http(s)://` href is accepted only for our own origin
(scheme, case-insensitive host, port). Otherwise the item is dropped with a warning. An
absolute path is used as-is. A relative href is resolved against the request URL. A literal `#` or
`?` is part of the name, never a fragment or query. This generalises the C# `#` → `%23`
fix-up (`ResponseParser.cs:59`, spec item 1) to `?` as well, which C# would truncate. The href is then
percent-decoded leniently: `%` not followed by two hex digits stays literal. The base prefix
is removed with an ASCII case-insensitive compare, because IIS returns different case. The
result is normalised (duplicate `/` collapsed, trailing `/` removed). An href outside the base
path, or one that decodes to a control character or a `.` / `..` segment, is dropped with a
warning. A hostile server cannot make us build a traversal URL.

**D7. Self-filter.** C# drops a *collection* whose re-resolved URL equals the request URL
under `CurrentCultureIgnoreCase` (`Client.cs:198-215`). That is culture-sensitive: under
`tr-TR`, `I` and `ı` fold differently, so `/MOVIES/` vs `/movies/` could leak the parent
into its own listing. We compare *decoded, normalised* paths with an **ASCII-only** case fold.
A Depth-1 child is one segment deeper than its parent, so a case-insensitive compare can
never confuse the parent with a child. The self entry is dropped whether or not it claims
to be a collection. If it is not a collection, a warning says the listed path is a file.

**D8. The PROPFIND body.** The default is C#'s `<allprop/>` (`Client.cs:28-42`), byte for byte.
`spwd_set_propfind_mode(1)` sends a `<prop>` list of exactly the eight properties we parse
(the list that is commented out in `Client.cs:33-41`, plus `iscollection` and `ishidden`).
Section 8 measures both on 10,000 entries.

**D9. XML: our own bounded pull parser (`src/spwd_xml.c`), no libxml2, nothing vendored.**
It is namespace-agnostic: the local name after the last `:` is compared ASCII
case-insensitively. That matches the C# `LocalName.ToLower()` (`ResponseParser.cs:49`) without
culture folding. It is XXE-proof by construction:
- any `<!DOCTYPE` (or any `<!` other than a comment or CDATA) rejects the document
  (`SPWD_ERR_XML`). There is no DTD, so there are no entity definitions, no billion-laughs
  and no external fetch. The parser has no I/O at all.
- the only entity references are the five predefined ones and numeric character references,
  which must be XML `Char`s. Any other `&name;` is an error ("undefined entity").
- limits: 64 nesting levels, 256-byte names, 1 MiB per text run, 64 KiB per captured
  property value, 64 MiB per response (`SPWD_MAX_XML`), 1,000,000 responses.
- structure: exactly one root, matching end tags (by full qname), nothing but whitespace /
  comments / PIs outside the root, no NUL bytes.
- encoding: UTF-8 (a BOM is skipped). `us-ascii` is accepted. A declared `iso-8859-1` /
  `latin1` is transcoded to UTF-8 first. Any other declared encoding, or a UTF-16 BOM, is
  `SPWD_ERR_XML`. Invalid UTF-8 inside text is replaced by U+FFFD with one warning. We do
  not reject: one bad name must not lose the whole directory. .NET's `XmlReader` throws and
  loses it.

**D10. DAV semantics, not token tricks.** The multistatus model is interpreted
structurally:
- `href` counts only as a direct child of `response`. C# takes *any* `href` element
  (`ResponseParser.cs:54-62`). So `<lockdiscovery>…<lockroot><href>`, `<owner><href>` and
  `<current-user-principal><href>` overwrite the item's href. C# skips only `checked-in` and
  `version-controlled-configuration` (`:136-139`). Finding C2.
- property values count only as direct children of `prop`, and only when their `propstat`
  `status` is 2xx (or absent). The values are buffered per `propstat` and committed on
  `</propstat>`, because `status` follows `prop`.
- a `response` without an `href` is dropped with a warning (spec item 5: C# NRE).
  Elements outside any `response` are ignored (C# NRE on `itemInfo.Href`).
- a `response`-level non-2xx `status` (for example 404 for a vanished member) drops that item
  with a warning.

**D11. `resourcetype` verdict.** A resource is a collection iff `resourcetype` has a child
element whose local name is `collection`, in any position. That covers empty
`<resourcetype/>`, whitespace, and `<redirectref/>` before `<collection/>`. C#'s
`Read()`-then-check-`LocalName` (`ResponseParser.cs:123-130`) looks only at the *first*
node after `<resourcetype>`. Section 8 shows where that breaks.

**D12. Is-collection precedence, and the `ContentLength == null` verdict.**
`is_collection` is decided by the first signal present:
1. `resourcetype` (RFC 4918 §15.9, mandatory for compliant servers),
2. `iscollection` (Microsoft extension; `1`/`0` and `true`/`false`, case-insensitive,
   `ResponseParser.cs:111-122`),
3. a trailing `/` on the href,
4. otherwise a file.
When `resourcetype` and `iscollection` disagree, `resourcetype` wins and a warning is
recorded. C# lets whichever comes later in the document win. **`getcontentlength` is never
used to decide.** Both SP2025 consumers use `ContentLength == null` as "is a folder"
(`WebDAVFolderFileAccesssor.cs:28,48`). That is wrong both ways: a server that omits
`getcontentlength` on a file shows it as a folder, and a server that sends it on a
collection shows the folder as an unbrowsable file. Section 8 lists which servers do which.
`spwd_item_content_length()` is -1 when absent, and the sprch item carries `folder`
from `is_collection` only.

**D13. Property parsing.**
- `getcontentlength`: optional surrounding whitespace, then digits only; `strtoull` plus a
  range check (≤ `LLONG_MAX`). Anything else is "absent" + a warning (spec item 8; C#
  `long.TryParse` accepts a sign and culture whitespace, `:93`).
- `getlastmodified`: RFC 1123 (`Sun, 06 Nov 1994 08:49:37 GMT`). The obsolete HTTP-date forms
  (RFC 850, asctime) are also accepted, as HTTP requires of recipients.
- `creationdate`: RFC 3339 / ISO 8601 `YYYY-MM-DDThh:mm:ss[.frac](Z|±hh:mm)`. A missing zone
  is taken as UTC with a warning.
- Each field falls back to the other field's format, with a warning, because servers mix
  them up. Everything else becomes -1 + a warning. C# `DateTime.TryParse`
  (`ResponseParser.cs:68,77`) accepts almost anything in the *current culture*, so
  `03/04/2020` means March or April depending on the user's locale. We reject it. Results
  are epoch milliseconds UTC; -1 means unknown.
- `displayname`: the text, or when empty or absent, the percent-decoded last segment of the
  href (`ResponseParser.cs:150-154`). C# uses `WebUtility.UrlDecode`, which also turns `+` into
  a space (C7). We do not.
- `hidden` / `ishidden`: an empty element, `1` or `true` means hidden; `0` or `false` means not
  hidden. C# sets `IsHidden = true` on the mere *presence* of the element (`:132-135`), so
  IIS's `<ishidden>0</ishidden>` marks every file hidden (C8).
- `getcontenttype`, `getetag`: text, as-is.
- `href` output (`spwd_item_href`) keeps the C# contract: `#` → `%23`, and a trailing `/`
  trimmed on non-collections (`:145-149`).

**D14. Accepted statuses, per verb.** These follow the C# exactly, except where marked.
- `PROPFIND`: 200 or 207 (`Client.cs:181,274`).
- `GET` range: 206, or 200 (`:593`). A 206 must carry a `Content-Range` whose start equals the
  requested start, otherwise `SPWD_ERR_HTTP`. On a 200 with `start > 0` the server ignored
  `Range`. C# hands the caller byte 0 as if it were byte `start` (C4). We skip `start` bytes
  in the stream, up to `SPWD_MAX_SKIP` (64 MiB), and warn. Beyond that it is `SPWD_ERR_HTTP`
  "server ignores Range".
- `PUT`: 200, 201, 204 (`:363-365`).
- `MKCOL`: 200, 201, 204; 409 is `SPWD_ERR_CONFLICT` (`:447-455`).
- `DELETE`: 200, 204 (`:492-493`).
- `MOVE` / `COPY`: 200, 201, **and 204**. C# rejects 204 (`:553-554,579-580`), but RFC 4918
  §9.8.5 / §9.9.4 answer 204 when the destination existed.
- A 207 on `DELETE` / `MOVE` / `COPY` is a partial failure: `SPWD_ERR_HTTP`.
- A 416 for a range that only *crosses* EOF (start < total, from `Content-Range: bytes */total`)
  is retried once with the end clamped to `total - 1`. RFC 9110 §14.1.2 says such a range is
  satisfiable; dufs answers 416 anyway (S1, section 8).

**D15. Error taxonomy** (`include/spwd.h`). The C# throws `WebDAVException` for everything
except the 409 on `MKCOL` (`WebDAVConflictException`), and callers catch broadly. We separate
the four UI outcomes:

| Code | When |
|---|---|
| `SPWD_OK` 0 | |
| `SPWD_ERR_TRANSPORT` -1 | backend returned -1 (DNS, refused, TLS, timeout) |
| `SPWD_ERR_HTTP` -2 | any other unexpected status (3xx, 405, 416, 5xx, 207-partial) |
| `SPWD_ERR_XML` -3 | response is not a parseable multistatus |
| `SPWD_ERR_AUTH` -4 | 401, 403 |
| `SPWD_ERR_NOT_FOUND` -5 | 404, 410 |
| `SPWD_ERR_CONFLICT` -6 | 409, 412 (`Overwrite: F`), 423 (locked) |
| `SPWD_ERR_NOT_ARMED` -7 | a write verb while writes are not armed; **no request sent** |
| `SPWD_ERR_UNSAFE_PATH` -8 | `..` / `.` segment, control byte, `\`, or a CR/LF in a header |
| `SPWD_ERR_NO_IO` -9 | no backend, or an `io` without the D1 extension |
| `SPWD_ERR_INVALID_ARG` -10 | NULL, bad range, bad URL, chunk too big |
| `SPWD_ERR_OOM` -11 | |

`spwd_last_http_code()` always keeps the status, so a UI can tell 416 from 500.

**D16. `translate: f` is spec.** `Download` and `DownloadPartial` send `translate: f`
(`Client.cs:305,325`). It is the IIS / SharePoint header for "the raw file, not a rendered or
executed one". Without it, IIS may execute an `.asp` file or return a rendered page instead of
its bytes. We send it on every `GET` and put it in `stream_url`'s headers. We also send it on
`PROPFIND`, as SKILL.md asks. Harmless elsewhere: Apache, nginx and dufs ignore it.

**D17. Never buffer a whole file.** `spwd_download_range(path, start, end)` (end inclusive,
like the HTTP header and the C# `DownloadPartial`) keeps at most `end - start + 1 ≤
SPWD_MAX_CHUNK` (16 MiB) bytes. `spwd_data(&len)` returns that chunk. A server that sends
more than asked is cut off by `on_body` returning stop. `spwd_download_to_file` streams through a
64 KiB-free path straight into `<local>.part`, then renames it into place. On failure the
`.part` is removed and a pre-existing `<local>` is untouched. `spwd_range_total()` reports the
file size from `Content-Range: bytes a-b/total` (-1 unknown).

**D18. Writes refuse unless armed.** `spwd_arm_writes(1)` is a separate explicit call; the
default is 0. When unarmed, `PUT` / `MKCOL` / `DELETE` / `MOVE` / `COPY` return
`SPWD_ERR_NOT_ARMED` *before* building a request, so nothing reaches the transport.
`spwd_fake_writes_sent()` counts write verbs the fake received, and `.console --test` asserts it
stays 0. The `sprch` handler never writes (it has no write entry points). `SPRCH_CAP_WRITES`
advertises that the library has armed-only ops, per the `sprch.h` definition.

**D19. `MOVE` / `COPY` send `Overwrite: F`.** C# sends no `Overwrite` (`Client.cs:541,567`), and
RFC 4918 defaults to `T`: a `MOVE` onto an existing name silently destroys the destination.
We make that a 412 → `SPWD_ERR_CONFLICT`. `Destination` is always an absolute URL on our
own origin, built from the D3 encoder, so it contains no CR, LF, space or control byte. That
holds by construction, and `fuzz_dest` checks it.

**D20. Collection URLs end in `/`.** `list`, `stat` of a collection, `MKCOL`, and `DELETE` /
`MOVE` / `COPY` of a path given with a trailing `/` all use a trailing slash (RFC 4918
§5.2). C# `CreateDir` strips it (`Client.cs:429-430` "Should not have a trailing slash"), and
nginx refuses `MKCOL` without one (section 8).

**D21. `PUT` with a range.** `spwd_upload_range(path, d, n, s, e)` requires `n == e - s + 1`
(inclusive, like `Content-Range`). C# checks `start + length == end`, which makes `end`
exclusive (`Client.cs:391`), and then sends `Content-Range: bytes start-end/*`
(`:671`): an off-by-one that claims one byte more than it sends (C6). `PUT` with
`Content-Range` is non-standard (RFC 9110 §14.5 lets servers reject it). Measured on live servers (section 8):
Apache honours it, nginx answers 501, Nextcloud 400, and **dufs and rclone ignore the header and
replace the whole file with the fragment** (S2). So a ranged PUT stats the file (Depth 0) before
and after. If the size shrank below `max(before, end + 1)`, it returns `SPWD_ERR_HTTP` "the server
ignored Content-Range and replaced the file". The damage cannot be undone, but it is never
silent. The C# reports success in the same case.

**D22. Auth.** Username and password go to the backend (`rq.username` / `rq.password`). libcurl
negotiates Basic or Digest. We never send `Authorization` ourselves, except in
`stream_url` output, where the player needs it. That header is `Basic`, the only scheme a URL
consumer can replay. `spwd_last_error()` and every `{"error":...}` are scrubbed of the
password and the `Authorization` value.

**D23. Request headers.** `User-Agent` defaults to `WebDAVClient/1.0.0.0` (`Client.cs:619`);
`spwd_set_user_agent` overrides it. `Connection: Keep-Alive` is dropped (C# sets it at
`:615`; libcurl reuses connections anyway). `spwd_add_header` rejects a CR, LF or NUL in the
value and any non-token name (`SPWD_ERR_UNSAFE_PATH`). The C# `headers.Add(keyValuePair)`
throws `ArgumentException` when a custom header duplicates `Depth` or `translate` (`:163-171`).
We let the engine's own header win and warn.

**D24. `sprch` settings** (legacy key names unchanged, `WebDAVRuntimeConfigHandler.cs`):
- `FullUrl`, when present, is the root: scheme, host, port and path (`:18,24-28`).
- otherwise, like `TestWebDAVConnection` (`:81-120`): `ServerUrl`, `ServerPort`, `UseHttps`
  (default `False`), and `Path`. `BasePath` is accepted as an alias. C# discards everything but the host from an
  absolute `ServerUrl` (`:113-116`). A user who typed `https://cloud.example.com/remote.php/dav`
  gets `http://cloud.example.com:80`, with no path and no TLS (C3). We take the scheme, port
  and path from `ServerUrl` when the explicit keys are absent. When present, the keys still
  win, so saved settings keep their meaning.
- `UserName` / `Password` are the credentials.

**D25. `sprch` entry points.**
- `validate`: resolve the URL (D24) and `PROPFIND` Depth 1 on the root (C# `client.List()`, `:130`).
  On success it returns `{"FullUrl":…, "RuntimeType":"WebDAV"}`, plus `"ID"` (a random UUIDv4)
  when `ID` is empty (`:135-140`).
- `list(folder_id)`: `""` is the root; otherwise a `path` from a previous `list`. Output is
  `{"items":[{"name","path","folder","size","mtime_ms","content_type","etag"}]}`. `size` and
  `mtime_ms` are -1 when unknown (spffa: never 0 for unknown). An invalid `folder_id` (D6
  rules) is `SPRCH_E_NOTFOUND`.
- `stream_url(entry)`: `{"url": <encoded absolute URL>, "headers": {"translate":"f",
  "Authorization":"Basic …"}, "size": n}`. No network when the entry carries `size`;
  otherwise one `PROPFIND` Depth 0 fills it in. C# always sends two `PROPFIND`s (base discovery +
  `GetFile`, `:58`).
- `download`: `SPRCH_E_NOTSUPPORTED` (`:34-37` returns null).
- caps: `LIST | STREAM | WRITES | VALIDATE` = `0x2B`. SKILL.md says `0xB`; sprch v1 added
  `CAP_VALIDATE` and this handler has one.

**D26. Status → `sprch` code.** AUTH → `E_AUTH`; NOT_FOUND / UNSAFE_PATH → `E_NOTFOUND`;
TRANSPORT and HTTP 5xx → `E_NETWORK`; 429 → `E_RATE`; XML, other HTTP and CONFLICT →
`E_PROTOCOL`; NO_IO → `E_NOTSUPPORTED`; bad settings → `E_CONFIG`; OOM → `E_NETWORK`.
Output that does not fit → `E_BUFFER`. A transport failure is never `SPRCH_OK` with an empty list.

**D27. JSON only through vendored yyjson** (`vendor/yyjson`, 0.10.0, unmodified). This covers
input settings / entries, `spwd_result_json` and all `sprch` output. Strings are sanitised
to valid UTF-8 before writing. An item whose *path* is not valid UTF-8 (a Latin-1 filename
on a Linux server) cannot round-trip through JSON. It is left out of `sprch` output with a
warning and stays available through the `spwd_item_*` C API.

**D28. Threading.** One process-wide lock around every stateful `spwd_*` export and every `sprch`
entry point. Returned `const char *` stay valid until the next call that changes the same
state. The fake has its own lock.

**D29. Exports** are exactly the list in `exports.json` (checked against
`nm -D --defined-only`). The build uses `-fvisibility=hidden` plus a version script. Names
follow the task (`spwd_*`), not SKILL.md's draft `spdav_*` stateless list. The `sprch` flat
wrappers are `spwd_sprch_{validate,list,stream_url,download}`, because `spwd_list` is taken.

## 3. Limits

| Constant | Value | Why |
|---|---|---|
| `SPWD_MAX_XML` | 64 MiB | a 10,000-entry `allprop` answer is ~7-12 MB (section 8) |
| `SPWD_MAX_CHUNK` | 16 MiB | one range read; playback asks for ≤ 4 MiB |
| `SPWD_MAX_SKIP` | 64 MiB | bytes we will discard when a server ignores `Range` |
| XML depth / name / text / value | 64 / 256 B / 1 MiB / 64 KiB | D9 |
| responses per multistatus | 1,000,000 | D9 |
| path | 4,096 B | also the upper bound after encoding × 3 |
| custom headers | 32 | |
| warnings kept | 64 (+ a count) | |

## 4. State machine (one call)

`arg check → (write? armed? else NOT_ARMED) → path check (D6/D3) → build URL + headers →
http->request (bounded sink) → status map (D14/D15) → parse (D9/D10) → href→path (D6) →
self-filter (D7) → store items + warnings → result JSON`.

## 5. Security notes

- XXE: D9. Header injection: D3/D19/D23 (paths are always encoded, header values checked).
- Traversal: D6 (server input) and D3 (caller input): `..`, `.`, `\`, control bytes → `UNSAFE_PATH`.
- Redirects are not followed (D1), so credentials never cross an origin.
- The C# accepts *any* TLS certificate (`ServerCertificateValidation` returns true,
  `Client.cs:767-774`, though it is not wired to the handler in this fork). libcurl verifies
  by default, and we keep it that way.

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

- Q1: canonical `sprch_conformance` from the registry repo (row 54) is not reachable from
  the cloud session. The local stand-in from the IPTV engine gates `make test`, as it did there.
- Q2: the D1 binding table is a bridge until sprch v2 carries the extension. Registry owner
  to decide.
- Q3: `PUT` with `Content-Range` (D21) is non-standard. Does SP2025 call `UploadPartial` at
  all? Neither consumer here does. If not, drop `spwd_upload_range`.
- Q4: should `MOVE` / `COPY` expose `Overwrite: T`? Nothing in the player needs it (D19).
- Q5: Digest auth on iOS `URLSession` works through the credential delegate. The Swift backend
  owner must confirm.

## 7. Findings

Every **C** finding was reproduced against the *unmodified* reference (`Client.cs`,
`ResponseParser.cs`, compiled by `tools/csharp-oracle`, driven the way SP2025 drives it) over real
HTTP. Evidence is in `tools/oracle/results/`. **S** = a server bug. **H** = this engine.

| ID | Sev | Where | Finding | Evidence |
|---|---|---|---|---|
| C2 | P0 | `ResponseParser.cs:54-62` | *Any* `<href>` in a response overwrites `Item.Href`: `lockdiscovery/owner`, `locktoken`, `lockroot`, `current-user-principal`. One `LOCK` (Windows Explorer, Office and Finder all take them) makes every item under the locked folder show as `opaquelocktoken:…`, and the folder vanishes from SP2025 navigation. | live Apache `LOCK`, `live-checks.md`; fixture `q-lockroot` |
| C5 | P0 | `WebDAVFolderFileAccesssor.cs:54-66,96-108` | The stream URL strips `BasePath` (decoded) from `Href` (encoded) with `StartsWith`. With a space, non-ASCII, or different case in the root path, the prefix does not match, so the base path is duplicated and **playback is a 404**. | live Apache root `/dav/Movies/Sub Folder`: C# URL → 404, C → 200 |
| C4 | P1 | `Client.cs:593` | `DownloadPartial` accepts 200. A server that ignores `Range` hands back the whole file **from byte 0** as if it were the requested start: corrupt seeks. | quirks `/norange`: C# 1,048,576 B starting `00 01 02…` for 300000-300099 |
| C10 | P1 | `Client.cs:44,652-655` | When `UserAgent` is unset (SP2025 never sets it), `Upload` / `UploadPartial` build `ProductInfoHeaderValue("WebDAVClient", AssemblyQualifiedName)`. That throws `FormatException` **before any request**: every upload fails. | all 5 servers, `live-checks.md` |
| C18 | P1 | `ResponseParser.cs:45-60` | One `<response>` without `<href>` is a `NullReferenceException` that loses the **whole directory** (spec item 5). | quirks `q-hrefs` |
| C15 | P2 | `ResponseParser.cs:123-130` | `resourcetype`: `Read()` then check `LocalName` sees only the first child. `<redirectref/><collection/>` and `<cal:calendar/><collection/>` become files and lose their trailing `/`. | quirks `q-resourcetype` |
| C16 | P2 | `WebDAVFolderFileAccesssor.cs:28,48` | `ContentLength == null` is the folder test. A file without `getcontentlength` becomes a folder. A collection with one becomes an unbrowsable 0-byte file. Overflow becomes a folder, and `-5` is a size. | quirks `q-length` |
| C1 | P2 | `Client.cs:210` | The self-filter uses `CurrentCultureIgnoreCase`. Under `tr-TR`, with the server's case differing (IIS), the folder is **listed inside itself**. | quirks `q-case` + `ORACLE_CULTURE=tr-TR` |
| C11 | P2 | `Client.cs:541,567` | `Destination` is `Uri.ToString()`, which is *unescaped*. A space goes raw into the header, so nginx and dufs refuse the `MOVE`. A non-ASCII name throws `HttpRequestException` before sending. | capture server + nginx/dufs rows |
| C12 | P2 | `Client.cs:553,579` | `MOVE` / `COPY` reject 204. nginx and dufs answer 204 on success, so C# throws **after** the operation happened. Without an `Overwrite` header the default is `T`: a copy onto an existing name silently replaces it, then reports failure. | nginx/dufs rows |
| C13 | P2 | `Client.cs:429-430` | `CreateDir` strips the trailing `/`, so nginx answers `MKCOL` with 409 (`WebDAVConflictException`). | nginx row |
| C9 | P2 | `ResponseParser.cs:136-139` | After `reader.Skip()` on `checked-in` / `version-controlled-configuration`, the loop's `Read()` swallows the **next** property. On SVN-backed servers `getcontentlength` is lost and the file shows as a folder. | quirks `q-lockroot/versioned.mkv` |
| C7 | P2 | `ResponseParser.cs:153` | The display-name fallback uses `WebUtility.UrlDecode`, which turns `+` into a space: `plus+sign.mkv` is shown as `plus sign.mkv` (Apache, quirks). | differential |
| C17 | P2 | `WebDAVException.cs:28-35` | Every constructor drops `httpCode`. Callers cannot tell 401 from 404 from 409 except by message text. | error-mapping table |
| C3 | P2 | `WebDAVRuntimeConfigHandler.cs:113-116` | An absolute `ServerUrl` keeps only its host: `https://…/remote.php/dav` becomes `http://host:80` with no path and no TLS. | unit tests (D24) |
| C19 | P3 | `ResponseParser.cs:68,77` | `DateTime.TryParse` in the current culture: `03/04/2020` is March 4 under invariant culture and April 3 under `de-DE`. asctime dates are dropped. | quirks `q-dates` |
| C8 | P3 | `ResponseParser.cs:132-135` | The mere presence of `ishidden` means hidden, so IIS's `<ishidden>0</ishidden>` hides every file. Unused by SP2025 today. | quirks `q-hidden` |
| C6 | P3 | `Client.cs:391,671` | `UploadPartial` sends `Content-Range: bytes s-e/*` with `e` exclusive: one byte more than the body. Apache tolerated it. | writes table |
| C14 | P3 | `Client.cs:538,564` | `MOVE` / `COPY` send the body `"MOVE"` / `"COPY"` labelled `text/xml`. | capture server |
| S1 | - | dufs 0.43.0 | 416 for a range crossing EOF. We clamp and retry (D14). | range table |
| S2 | - | dufs 0.43.0, rclone 1.60.1 | `PUT` + `Content-Range` **replaces the file** with the fragment (should be 400 / 501). Detected (D21). | writes table |
| S3 | - | dufs 0.43.0 | `COPY` with `Overwrite: F` onto an existing file overwrites it (204). Nothing a client can do. | writes table |
| S4 | - | rclone lsjson, cadaver | A literal `#` or `?` in an href truncates the name (`My `, `what`): the reason the C# `%23` fix-up exists. We keep both characters literal (D6). | quirks `q-names` |
| H1 | fixed | this engine | The first ranged-PUT post-check compared only against `end + 1`, so a truncation at offset 0 (dufs, rclone) looked fine. Found by the live run and fixed with a pre-stat. | writes table |

## 8. Measurements and verdicts

Servers: Apache 2.4.58 mod_dav, nginx 1.24.0 + dav_ext, dufs 0.43.0, rclone 1.60.1 serve webdav,
Nextcloud 35.0.1 (docker), all on loopback. The quirks server is `tools/oracle/quirks_server.py`.
Client oracles: rclone lsjson 1.60.1, cadaver 0.24, and the shipped C# on .NET 8.0.131. Full tables are in
`tools/oracle/results/differential.md` and `live-checks.md`.

**`resourcetype` verdict.** The C# `Read()` trick holds on all five real servers: each one
emits `<collection/>` as the first and only child. It fails on `<redirectref/>`-first and
`<calendar/>`-first (C15). It is masked in SP2025 only because the consumer ignores
`IsCollection` (C16). D11 (any `collection` child) is right everywhere.

**`ContentLength == null` vs `IsCollection` verdict.** `IsCollection` is right. With
`<allprop/>`, none of the five servers sends `getcontentlength` on a collection, and all five
send it on every file, so none of them disagrees. The consumer test is therefore correct *by
accident* on these servers and wrong on the quirks in both directions (C16). IIS (reported to
send `getcontentlength` 0 on folders) could not be reached from the sandbox.

**Listing differential** (`/Movies`: `#`, `%`, `?`, `+`, `&`, quotes, CJK, a 0-byte file, a
subfolder). The C engine, rclone and cadaver agree on all 11 items on all five servers. The C#
differs only on Apache's `plus+sign.mkv` (C7). Apache and Nextcloud encode CJK in lower-case hex,
and nginx, dufs and rclone in upper case. Apache, nginx and rclone leave `+`, `&` and `'` raw, and
dufs encodes them. No server emitted a raw `#`, `?`, `%`, space or CJK in an href. Those came only
from the quirks server, and the D6 rules handle them (the `%23` fix-up is generalised, not broken).

**Range GET** (64 MiB file, compared byte-for-byte with `dd`): the first 1 MiB, 4 MiB at 32 MiB,
across EOF, beyond EOF (416 with total) and the last byte are all equal on all five servers. That
includes dufs after the S1 retry. A server that ignores `Range` gives the correct bytes through the
D14 skip; the C# gives byte 0 (C4).

**10,000 entries, `<allprop/>` vs `<prop>`** (C engine, best of 5):

| server | allprop bytes / ms | prop bytes / ms | client CPU ms | peak RSS |
|---|---|---|---|---|
| Apache | 8,368,368 / 202.7 | 6,928,282 / 189.1 | 60 | 26.2 MB |
| nginx | 4,529,500 / 63.0 | 3,969,444 / 60.0 | 36-40 | 24.6 MB |
| dufs | 3,959,443 / 508.5 | 3,959,443 / 522.0 (body ignored) | 36 | 25.5 MB |
| rclone | 6,338,043 / 310.4 | 6,568,167 / 293.0 | 58 | 25.7 MB |
| Nextcloud | 4,459,657 / 976.7 | 6,899,805 / 1,062.5 | 47-56 | 27.4 MB |

The process baseline is 7.7 MB. **`<prop>` is not materially faster:** 4-7 % on Apache, nginx
and rclone. It makes no difference on dufs, which ignores the body. It is **9 % slower and 55 %
larger on Nextcloud**, which answers every property it does not know with a 404 propstat. Wall time
is dominated by the server. Client parse cost is 36-60 ms and ≤ 20 MB for 10,000 entries.
Decision: keep `<allprop/>` as the default, and keep `spwd_set_propfind_mode(1)` as an option.

**Base-path discovery** (spec item 4, `Client.cs:698-704`): `_encodedBasePath` is cached per
`Client`. A 10,000-entry `List` costs one discovery `PROPFIND`, not one per collection. But SP2025
builds a new `Client` per root folder, per validate and per playback, so every playback pays two
`PROPFIND`s before the `GET`. We pay zero (D4, D25).

**XXE.** A billion-laughs fixture and an external-entity fixture (`file:///etc/passwd` plus an
`http://` entity pointing at the quirks server) are both rejected at byte 22 with "DTD or markup
declaration rejected (XXE guard)". The quirks server's fetch counter stayed at 0. .NET's default
`XmlReader` also refuses DTDs (`DtdProcessing.Prohibit`).

**Fuzzing** (`tools/oracle/results/fuzz-coverage.txt`): `fuzz_xml` ran 2,029,078 runs and reached
98.4 % of `spwd_xml.c`, 98.2 % of `spwd_dav.c` and 100 % of the lines of `href_to_path`. `fuzz_dest`
ran 2,333,386 runs and reached 100 % of `spwd_c_url` and 92.9 % of `spwd_c_move_copy`. Both reported
0 findings. Coverage came from source-based replay of the final corpora.
