zapret-kvn/docs/RUNTIME_MODULES.md
loop-uh e18064bd7d
Some checks failed
Windows project source guards / test (push) Has been cancelled
Keep lazy imports reading the running exe after it is replaced
PyInstaller reopens the exe by name for every lazy import. When another file
took that name while the app ran, the next lazy import read the new file at
the old offsets: field check #3 (2026-11-23) found 15 crashes on
0.8.102-0.8.107 (crash:error = zlib.error at pyimod01_archive.extract:134,
crash:OSError at extract:119) in start_metrics_worker and the disconnect
cleanup, often seconds from a failed update on the same install.

frozen_archive.install gives PyInstaller's archive reader one descriptor to
the original file, opened with FILE_SHARE_DELETE, so renaming or deleting the
exe works as before and imports keep reading this build. The first time the
name points at another file the app logs it and notes the app error
update:exe_replaced, so whatever swaps files under a live app stays visible.

Proof: tests/test_frozen_archive.py (PyInstaller's own reader crashes
unpinned and reads the original pinned, on the build VM with PyInstaller
6.21) and a frozen onedir probe on win10 (unpinned zlib.error, pinned OK).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 04:13:46 -05:00

67 lines
11 KiB
Markdown

# Protocol runtimes and original errors
The source layout on both platforms is documented in [SOURCE_LAYOUT.md](SOURCE_LAYOUT.md). The folder migration is complete; WG/AWG transport validation and the combined stable release are separate gates.
## Architecture basis (owner decision 2026-11-04)
Each protocol runs on its own complete native core, so that everything works as correctly as possible. sing-box is only the intermediary gasket: the owner of TUN, routing, DNS and protected sockets, and the glue between the native cores and the system. Do not reimplement or approximate a protocol in sing-box or in app code when its native core exists. More native cores will be added over time, one per protocol that needs it; a new core is a new protocol owner behind the same gasket, not a replacement for sing-box. The Xray and Hysteria helper processes on Windows are deliberate.
The transport owner is fixed on both platforms: VLESS, VMess and Trojan go to the official Xray core (owner decision 2026-11-16: sing-box has no XHTTP for them and only approximated the rest), Hysteria2 to the official Hysteria core, WG/AWG to the official Amnezia device/netstack, and the remaining protocols to sing-box. Plain WG uses Amnezia with AWG extensions absent. The only routing, DNS and TUN owner on both platforms is sing-box. Its active native JSON owns domain rules and geosite-derived native `.srs` rule sets in both proxy and TUN modes. Xray and Hysteria implement only the selected proxy transport, never a second routing policy. Core selection is not a capability probe or an automatic fallback between protocol implementations.
Protocol adapters retain the original imported URI. Xray needs native JSON, so its adapter translates the URI at that boundary; it must not translate it through sing-box first. On Android the cores are embedded libraries behind the same outbound interface; sing-box owns the only TUN and protected sockets.
Legacy Windows Xray-front and tun2socks selections migrate to sing-box. Existing raw Xray configuration files are retained, not translated or overwritten. Auto connect is disabled during that migration: users must review their sing-box rules before explicitly reconnecting. Existing sing-box users keep auto connect.
## IPv6 to the VPN server first (owner decision 2026-11-22)
A server's IPv4 address is often blocked by address while its IPv6 address still works. With the setting «IPv6 к серверу первым» (Settings → network, on by default) and a native global IPv6 address on the PC's uplink (`xray_fluent/network/server_family.py`, adapter data only, no probe), each core gets IPv6 first in its own native way:
- sing-box native outbounds: `domain_resolver: {server, strategy: prefer_ipv6}` (`_ensure_proxy_server_bootstrap_contract`); sing-box races IPv6, then IPv4 after 300 ms or at once on failure. WG endpoints are unchanged.
- Xray (hybrid, dialed by sing-box through the protect inbound): app `resolve` rules on the protect inbound with `network: tcp` and `strategy: prefer_ipv6` for every server name; the direct outbound races the families. UDP keeps its previous order (one socket, no way back).
- Core patch `core-patches/address-family-memory.patch` (same `common/familymemory` as Android 0020): the family that last worked for a server name starts first; cleared on a network change and after 30 minutes.
- Hysteria2 (`hysteria.exe` with a pinned address): IPv6 pinned first when the start verifies the server; no authentication within 4 s (or all probes failing earlier) restarts the attempt pinned to IPv4 and remembers the IPv6 failure in `server_family.MEMORY` (reset on a network change).
- Latency probes: one family per temporary core (Xray `UseIP` used to pick at random among both families), with IPv6 first the native race (Xray `happyEyeballs`, sing-box `prefer_ipv6`); the Hysteria probe pins IPv6 only once IPv6 has worked for that server.
- Amnezia (WG/AWG, `zapret-amnezia.exe`, one peer): the app resolves the peer and passes the preferred family as `address` (from `server_family.MEMORY`, IPv6 when nothing is remembered) and the other family as `race_address`. The helper's bind (`runtime/amnezia/family_race.go`, same code as Android patch 0021) sends the first handshake to both; the server answers one copy (the second is a replay for it) and the bind keeps that family for the session. Unanswered retries alternate families, so a family that loses only the replies cannot win every time. The helper reports only the family (`address_family` event, never the address) and the app remembers it. No added delay and no restart, unlike the Hysteria2 fallback.
- Not changed: slot helper processes, Xray standalone mode (Go's own RFC 6555 dial with the system resolver order).
## Errors
`xray_fluent/diagnostics/runtime-errors.json` and Android's `app/src/main/resources/runtime-errors.json` are the same catalog. An error is evidence first: component, operation stage, original message, session generation and a target identity only when the producer can prove it. The catalog supplies classification, never replacement prose. Unknown messages remain visible.
The error journal is separate from bounded traffic/debug logs. It retains each distinct error during the application process lifetime and counts repeats. The UI and diagnostic export use this journal without the traffic-log limit. Passwords, private keys, tokens and credential-bearing URIs are redacted. Release verification must exercise real producer, observer, journal and UI/export boundaries; direct reducer tests alone do not verify this contract.
Loopback TCP resets/EOF are retained as `LOCAL_CLIENT_CONNECTION_CLOSED` with `record_only` policy. They cannot consume Hysteria recovery or turn successful HTTPS readiness into a server failure. A real process exit remains terminal; TLS/auth/pin failures retain their higher-priority security classification.
## Source-built sing-box UDP fix
`core-patches/sing-udp.json` pins upstream sing module versions, zip/patch hashes and the packet regression test shared with Android. The private patched module receives complete UDP datagrams in both normal and low-memory builds, reserves transport header space in addition to payload, and uses packet-size buffers for connected UDP read waiters. TCP buffers are unchanged. UDP buffers grow to 64 KiB (plus required header space), so in-flight UDP memory use increases.
The Go cache is never patched in place. An unknown dependency version or changed cached source fails the build. Windows bundle cache keys include adapter source, patches, tests and build tools, not only upstream versions. Android AAR freshness includes `CORE_UDP_PATCH_SHA256`. Remove the patch only after the same full-chain packet tests pass against an upstream fix.
## Coordinated stable preparation
Before validation and the final source commits, run from the Windows checkout:
```bash
python3 scripts/prepare_core_release.py --windows-version 0.5.8 --android-tag v0.3.27
```
Use the next actual unpublished versions. Each new pair checks official upstream tags (Amnezia prereleases allowed), updates the two pins and writes the identical `core-release-freeze.json` to both repositories. Repeating that pair validates the receipt offline, without selecting a newer tag. API/dependency incompatibility must be repaired and tested before committing or publishing; no old-core fallback.
Then run all platform gates, commit/push all ready source and use the existing Windows runner and Android stable publisher. The Windows runner reuses a matching freeze; the Android publisher requires its tagged source to match the freeze. Installed apps receive these built cores with the app update only.
### Partial (delta) app updates
The release signer (`sign_release` in `scripts/release_windows.py`) puts every file of the release ZIP (path, size, SHA-256) into the signed `update-manifest.json`. `xray_fluent/updates/delta_zip.py` uses that list: the updater reads the ZIP central directory by HTTP Range, reuses installed files whose SHA-256 equals the signed one, downloads only the other entries and accepts each of them only if its size, CRC-32 and SHA-256 match the signed list. Any doubt (no Range, other file set, bad hash, more than 60% of the archive) falls back to the whole-ZIP download that is checked against the signed archive SHA-256 as before.
The patched `sing-box.exe` must stay byte-identical when its sources are unchanged, otherwise ~33 MB are downloaded in every update. `build_singbox_front.py` therefore passes the patched `sing` dependency to `go mod edit -replace` as a path relative to the source tree (Go writes that path into the executable) and refuses a binary that embeds its temporary build directory.
### A replaced exe under a running app
PyInstaller reopens the exe by name for every lazy import (`pyimod01_archive.ZlibArchiveReader.extract`). When another file takes that name while the app runs, the next lazy import reads the new file at the old offsets and the app crashes: field check #3 (2026-11-23) found 15 such crashes on 0.8.102-0.8.107 (`crash:error` = `zlib.error` at `extract:134`, `crash:OSError` at `extract:119`), in `start_metrics_worker` and in the disconnect cleanup, often seconds from a failed update on the same install. `main.py` therefore calls `xray_fluent/platform/frozen_archive.install` right after the exception hooks: the archive reader keeps one descriptor to the original file, opened with `FILE_SHARE_DELETE`, so renaming or deleting the exe works as before and imports keep reading this build. The log line `Module archive pinned to the running exe` shows it acted; the first time the name points at another file the app logs `[update] The program file was replaced while running` and notes the app error `update:exe_replaced`, so the program that swaps files under a live app stays visible in the field. Proof: `tests/test_frozen_archive.py` (PyInstaller's own reader crashes unpinned and reads the original pinned; it runs where PyInstaller is installed, as on the build VM) and a frozen onedir probe built with PyInstaller 6.21 on win10 (unpinned: `zlib.error` after the exe was replaced; pinned: the lazy import worked).
## Android audit observations
The existing Hysteria adapter emits `server certificate SHA-256 mismatch` but the old Android classifier required the substring `pin`. It therefore lost the security classification and could show the subsequent generic HTTPS failure as VPN-200. The shared catalog covers the adapter and official executable texts.
The protected domain UDP dialer returns a NAT wrapper that loses the numeric sender address (`127.0.0.1:port` becomes `:port`). A loopback boundary test reproduces this. A local official Hysteria plain handshake and TCP echo still pass through that wrapper, so this is not proof of the reported device failure. Android ADB is currently unavailable; no device reproduction has been claimed.