fix: eliminate reconcile fork-storm (OOM) + resolve UCI config conflict with xray-core
build / aarch64_cortex-a53 (push) Successful in 3m0s
build / x86_64 (push) Successful in 2m59s

Two release-blocking defects found via live 512M OpenWrt VM testing.

1) Fork-storm / OOM (critical). Reconcile() -> reloadXray() ->
   "/etc/init.d/shater reload" -> reload_service -> shater_reconcile ->
   `xrayctl reconcile` -> Reconcile() was an infinite mutual recursion; each
   level blocked on CombinedOutput and spawned a process (854x reconcile +
   853x reload observed), exhausting RAM and pinning both vCPUs -> OOM-killer.
   - Reconcile() no longer calls reloadXray(); procd's file-watch on run.json
     restarts xray. Reconcile runs inside the init lifecycle, so calling the
     init back is the recursion.
   - reloadXray() now runs `/etc/init.d/shater start` (not `reload`); it is only
     invoked from Apply()/Rollback() (LuCI/ubus/CLI), never the init lifecycle.
   - init reload_service() simplified to start/stop (dropped the double reconcile).
   Verified: `xrayctl apply` 0.39s (was >185s hang); 93 procs / load 0.00 stable
   with an active 254-node config on 512M; xray binds :10853 API + :12345 tproxy.

2) UCI config namespace clash. shater shipped /etc/config/xray, which collides
   with the xray-core dependency's own /etc/config/xray (opkg dropped ours to
   /etc/config/xray-opkg, so the schema never took effect). Renamed the UCI
   namespace xray -> shater everywhere (Go uci export/commit, all 11 LuCI views +
   acl, init scripts, hotplug, Makefile conffiles, examples). Runtime paths
   (/etc/xray/run.json, /usr/share/xray), the xray-core package, and the ubus
   object name are intentionally unchanged.

Also: ci/pack-xrayctl.sh (local ipk packer) with a postinst chmod so the binary
is executable regardless of host-tar mode handling; PKG_RELEASE bumped to r3.

Verified end-to-end on a fresh 512M OpenWrt 24.10.3 VM: feed install
(opkg install luci-app-shater pulls xrayctl+shater-core), real LAN client
(netns in br-lan) proxied through a live subscription node -> exit IP changed
(104.156.233.234 vs 45.131.214.140 direct); per-client nft counters + xray
stats API populated. See PROOFS.md.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
omarandClaude Opus 4.8 committed 2026-07-09 11:36:48 +03:00
1 parent 71a6f127a1
commit 05920f83ad
37 files changed
+259 -103

No files matched your search

+1
View File
@@ -26,3 +26,4 @@ Thumbs.db
# windows reserved-name junk from stray > NUL redirects
NUL
nul
out/
+2 -2
View File
@@ -48,7 +48,7 @@ target chain|group|node|direct|block + egress. Per-client policy. Explain/trace
- НЕ per-node процессы. НЕ legacy iptables. MVP НЕ включает цепочки/FakeIP/расписания (фаза 2+).
## Как грамотно строить план (методология)
1. **Contract-first.** Сначала зафиксировать «контракт»: UCI-схему `/etc/config/xray` +
1. **Contract-first.** Сначала зафиксировать «контракт»: UCI-схему `/etc/config/shater` +
интерфейс `xrayctl` (CLI+ubus). От модели зависит ВСЁ (генератор, фаервол, UI, тесты) —
это корень зависимостей, начинаем с него.
2. **Walking skeleton (вертикальный срез).** Тончайший сквозной путь, доказывающий
@@ -79,7 +79,7 @@ DNS-leak · tproxy-петля (sockopt.mark) · flow-offload ломает tproxy
kmod↔ядро pin · дрейф схемы xray · boot-order (fw→dnsmasq→xray+hotplug) · lockout (→ commit-confirm).
## Ближайшие 3 шага
1. Написать **спеку контракта**: UCI-схема `/etc/config/xray` + командный/ubus-интерфейс `xrayctl`.
1. Написать **спеку контракта**: UCI-схема `/etc/config/shater` + командный/ubus-интерфейс `xrayctl`.
2. Завести **скелет репозитория** в `shater/` (git init, структура из дока 02) + CI-заготовка.
3. Поднять **QEMU-стенд** (OpenWrt x86-64 + тест-клиент) и собрать пустой пакет через SDK (WSL2).
</content>
+3 -3
View File
@@ -37,7 +37,7 @@ xray-core (наша экспертиза: reality/xhttp/vision). Генерат
- Рекомендация: **B** для парсинга подписок + генерации, **ucode** для склейки UCI→JSON.
Либо целиком Go-хелпер `xrayctl` (sub-fetch + build + validate `xray -test`).
### 3. UCI-схема `/etc/config/xray`
### 3. UCI-схема `/etc/config/shater`
Секции: `node` (сервер), `subscription` (url+headers+layer), `chain` (L1..Ln),
`policy` (правила роутинга/сплит), `inbound` (tproxy/socks/http), `dns`, `global`.
LuCI правит UCI → генератор рендерит xray JSON.
@@ -103,11 +103,11 @@ IPv6; миграция конфигов при апгрейде; тесты на
1. **`xrayctl`** (Go, отдельный пакет через golang-package.mk):
- `sub fetch` — тянет подписку(и) с заголовками (Happ HWID/UA), кеш.
- `sub parse` — share-links → xray-outbounds (libXray).
- `build` — из UCI `/etc/config/xray` собирает полный JSON (inbounds+routing+dns+balancer).
- `build` — из UCI `/etc/config/shater` собирает полный JSON (inbounds+routing+dns+balancer).
- `test` — `xray -test` перед применением.
- `apply` — пишет конфиг, дёргает reload сервиса.
- `status`/`nodes` — отдаёт JSON (observatory latency, active node) для UI.
2. **UCI `/etc/config/xray`**: секции `global`, `subscription`, `node`, `inbound`,
2. **UCI `/etc/config/shater`**: секции `global`, `subscription`, `node`, `inbound`,
`dns`, `policy` (routing), позже `chain`.
3. **procd** `/etc/init.d/xray` — xray run + respawn + reload-on-file.
4. **fw4** `/etc/nftables.d/` — tproxy TCP+UDP, дисциплина меток, разрыв петли (sockopt.mark).
+1 -1
View File
@@ -36,7 +36,7 @@ Evidence is `file:line` or `func`. "Rendered" = ends up in the xray JSON, the
| failover (priority order) | **STUB** | `generate.go:628`: `failover` is aliased to xray `leastLoad` — this is **not** a priority-ordered failover. | Emit real failover (ordered member list / `strategy:leastLoad` with costs, or observatory-driven priority). |
| Observatory config emitted | **PARTIAL** | `generate.go:103-108` emits `observatory{subjectSelector,probeURL,probeInterval}` only when a leastping/failover group exists. | OK; but see below — results never surfaced. |
| Live ping / alive surfaced in UI | **MISSING** | `status.go:38 NodesJSON` sets `Alive=false, LatencyMS=0` always; observatory results (xray API) are never read. `node_test` (`status.go:70`) does a **plain TCP connect to the endpoint**, not a through-node real-delay. | Read xray Observatory/`StatsService` over the API port and merge into `nodes`. |
| Group CRUD from UI | **MISSING** | No `groups.js` (menu.d has overview/nodes/subscriptions/rules/settings only). Groups exist only by hand-editing `/etc/config/xray`. | Add a Groups LuCI page (strategy, source, members, include/exclude, probe). |
| Group CRUD from UI | **MISSING** | No `groups.js` (menu.d has overview/nodes/subscriptions/rules/settings only). Groups exist only by hand-editing `/etc/config/shater`. | Add a Groups LuCI page (strategy, source, members, include/exclude, probe). |
## 3. Multi-hop chains L1→L2→L3
+3 -3
View File
@@ -1,11 +1,11 @@
# CONTRACT (0c) — UCI-схема `/etc/config/xray` + интерфейс `xrayctl`
# CONTRACT (0c) — UCI-схема `/etc/config/shater` + интерфейс `xrayctl`
Контракт, от которого зависит весь код. UCI = desired state; `xrayctl` рендерит из него
xray JSON + nft + policy-routing и применяет атомарно.
## Файлы на устройстве
```
/etc/config/xray # UCI desired state (редактирует LuCI/пользователь)
/etc/config/shater # UCI desired state (редактирует LuCI/пользователь)
/etc/xray/run.json # сгенерированный боевой конфиг xray
/etc/xray/last-good.json # последний валидный (для rollback)
/etc/xray/subs/<name>.json # кеш нод подписки (после parse+reconcile)
@@ -15,7 +15,7 @@ xray JSON + nft + policy-routing и применяет атомарно.
/usr/bin/xray # движок (не наш, зависимость)
```
## UCI-схема (`/etc/config/xray`)
## UCI-схема (`/etc/config/shater`)
### globals (одна секция)
```
+98 -1
View File
@@ -33,4 +33,101 @@
`ruleset update [name]` (агенты C экспортируют функции, main.go — на мне).
- Согласовать shape stats JSON (агент B) ↔ overview.js (агент D): `stats.nodes[]/clients[]/rules[]`.
- Рабочая нода для E2E: пере-найти через observatory на момент проверки (ноды живут недолго).
</content>
## ✅ ПОЛНЫЙ END-TO-END через плагин (интегрированный T1-код, 2026-07-09)
Конфиг: 50 реальных нод из подписок → группа `main` (leastPing) → tproxy-правило. `xrayctl apply`.
```
xrayctl nodes (via xray API): 39 alive (live-ping/alive реально работает)
LAN client (netns 192.168.1.60 в br-lan) exit: 116.203.69.142 (проксировано через живую ноду)
router direct exit: 45.131.214.140 (mgmt-bypass: НЕ проксирован)
```
Вывод: трафик реального LAN-клиента прошёл через плагин (nft tproxy → xray balancer → живая нода) —
**exit-IP сменился**. Полный keystone цели закрыт.
## ✅ mgmt-bypass (router-egress не ломается при apply) — фикс B
При активном tproxy: `wget https://api.ipify.org` с роутера → `45.131.214.140`, SSH жив,
`fib daddr type local accept` в nft. Раньше был «Operation not permitted» — починено.
## ✅ Статистика per-client / per-inbound / per-node
После клиентского трафика:
```
nft set clients: { 192.168.1.60 counter packets 69 bytes 6533 }
xrayctl stats: clients:[{ip:192.168.1.60,bytes:6533,packets:69}], inbounds:[{name:lan,c_in_lan,...}], nodes:[...] (xray Stats API)
```
## ✅ Генератор со всеми T1-фичами → реальный xray -test
Конфиг с egress-binding(interface) + resolvers(doh/fakeip+pool) + dns_rule(geosite) + kill-switch(closed)
+ stats/api + observatory → `xray -test: Configuration OK` (с установленными v2ray-geoip/geosite).
Фичи в run.json: api, stats, policy, observatory, fakedns, egress-viawan, sockopt.
---
## ✅ КРИТИЧЕСКИЙ ФИКС: fork-storm/OOM в reconcile (2026-07-09, 512M VM)
**Симптом:** после `xrayctl apply`/на буте VM (512M) уходила в 100% на обоих vCPU,
жуткий лаг; `ps` → OOM-killer. Причина: **бесконечная взаимная рекурсия**
`Reconcile() → reloadXray() → «/etc/init.d/shater reload» → reload_service →
shater_reconcile → xrayctl reconcile → Reconcile() → …`. Каждый уровень блокируется на
`.CombinedOutput()` и плодит процесс → **854×`xrayctl reconcile` + 853×`sh …/shater reload`**
→ форк-бомба → исчерпание памяти.
```
до фикса: 5239 процессов, loadavg ~200, docker CPU 216%, OOM-killer в логе ядра
```
**Фикс (код):**
- `apply.go Reconcile()` больше НЕ вызывает `reloadXray()` (procd сам рестартит xray по
file-watch на run.json). Reconcile вызывается ИЗ init-цикла → обратный вызов init = рекурсия.
- `apply.go reloadXray()` теперь `/etc/init.d/shater start` (не `reload`); зовётся только из
`Apply()`/`Rollback()` (LuCI/ubus/CLI), не из init-цикла → рекурсии нет.
- init `reload_service()` упрощён до `start`/`stop` (убран двойной reconcile).
**Проверено вживую (512M, активный конфиг из 254 нод):**
```
xrayctl apply → real 0m0.39s (было: вис >185s)
после apply: 93 процесса, loadavg 0.00 (стабильно 3× замера)
xray слушает: 127.0.0.1:10853 (API) + :::12345 tcp/udp (tproxy)
nft inet shater = OK; ip rule: from all fwmark 0x2000 lookup shater
```
## ✅ ФИКС КОНФЛИКТА ПАКЕТОВ: UCI-namespace `xray` → `shater` (2026-07-09)
**Симптом:** `opkg install` клал shater-конфиг в `/etc/config/xray-opkg`, активным
оставался стоковый `/etc/config/xray` пакета **xray-core** (зависимость). Конфликт
conffile: два пакета владели `/etc/config/xray`.
**Фикс:** UCI-namespace переименован `xray` → `shater` во всём коде (Go `uci export/commit`,
LuCI `form.Map/uci.*` во всех 11 view + acl, init-скрипты, hotplug, Makefile/conffiles,
examples). Рантайм-пути (`/etc/xray/run.json`, `/usr/share/xray`, бинарь/пакет `xray-core`,
ubus-объект `xray`) НЕ тронуты. `go build`+`gofmt`+`go test` зелёные.
```
после: /etc/config/shater (1202B, схема shater) — конфликта нет; uci show shater OK
```
## ✅ ПОЛНЫЙ FEED-ФЛОУ на чистом OpenWrt 24.10.3 (512M, свежий диск)
`vm-start.ps1 -Fresh` → pristine OpenWrt → штатная установка:
```
opkg install: xray-core kmod-nft-tproxy kmod-nft-socket ip-full kmod-veth v2ray-geoip
v2ray-geosite luci dnsmasq-full openssh-sftp-server (из офиц. репозиториев)
src/gz shater file:///tmp/shfeed → opkg update → opkg install luci-app-shater
→ подтянул xrayctl (r3) + shater-core (r3) из фида; /etc/config/shater установлен корректно
xrayctl исполняемый (postinst chmod), xrayctl gen читает shater-config (260 тегов)
```
## ✅ KEYSTONE E2E — реальный LAN-клиент → плагин → живая нода → EXIT-IP СМЕНИЛСЯ
Подписка пользователя `pro.qomar.pw` → `xrayctl sub update sub0` → **254 ноды** в кеш →
группа `main` (leastPing) → правило `def`→group:main → inbound `lan` tproxy → `xrayctl apply`.
LAN-клиент = netns `shater_lan` (192.168.1.60), veth в br-lan (реальный transit).
```
LAN-клиент exit (через плагин): 104.156.233.234
роутер direct exit (mgmt-bypass): 45.131.214.140
```
**Exit-IP реального LAN-клиента сменился** → трафик прошёл nft tproxy → xray balancer →
живую ноду подписки. Полный путь плагина доказан на 512M без шторма.
## ✅ Статистика per-client / per-inbound / per-node (живой трафик)
```
nft set clients: { 192.168.1.60 counter packets 18 bytes 1134 }
xrayctl stats: clients:[{ip:192.168.1.60,bytes:1134,packets:18}],
inbounds:[{name:lan,counter:c_in_lan,packets:18,bytes:1134}], nodes:[…xray API…]
xrayctl nodes: per-node JSON {name,group,proto,tag,alive,latency_ms,selected,fingerprint,stale}
```
+2 -2
View File
@@ -34,13 +34,13 @@
## Код, контракт, сборка
| Файл/дир | О чём |
|----------|-------|
| [CONTRACT.md](CONTRACT.md) | UCI-схема `/etc/config/xray` + интерфейс `xrayctl` (CLI+ubus) |
| [CONTRACT.md](CONTRACT.md) | UCI-схема `/etc/config/shater` + интерфейс `xrayctl` (CLI+ubus) |
| [STATUS.md](STATUS.md) | Что собрано и **чем проверено** (доказательная база) |
| [BUILD.md](BUILD.md) | Сборка `.ipk` (SDK/CI) + установка на роутер |
| `xrayctl/` | Go control-plane (парсер, генератор, apply) |
| `shater-core/` | Системный пакет (procd/hotplug/sysctl/дефолт-конфиг) |
| `luci-app-shater/` | LuCI-приложение (JS-views + ubus-бэкенд) |
| `examples/` | Примеры `/etc/config/xray` + share-link фикстуры |
| `examples/` | Примеры `/etc/config/shater` + share-link фикстуры |
| `.github/workflows/build.yml`, `dist/` | CI (gh-action-sdk) + фид |
## Статус
+2 -2
View File
@@ -8,12 +8,12 @@
|-----------|-----|---------------|--------|
| `xrayctl` | Go control-plane (парсер share-link, генератор, UCI, sub, apply, status) | `go build`+`go vet`+`go test` (13 тестов) зелёные; `selftest` 8/8 | ✅ |
| — генератор (links) | share-links → xray JSON | **реальный `xray -test` 25.1.30 → `Configuration OK`** | ✅ |
| — генератор (UCI) | `/etc/config/xray` → xray JSON | **реальный `xray -test` → `Configuration OK`** | ✅ |
| — генератор (UCI) | `/etc/config/shater` → xray JSON | **реальный `xray -test` → `Configuration OK`** | ✅ |
| `shater-core` | procd init, hotplug, sysctl, инертный дефолт | `sh -n`; **`.ipk` собран в SDK** (`shater-core_0.1.0-r1_all.ipk`) | ✅ |
| `luci-app-shater` | JS-views + ucode ubus-бэкенд + ACL | JSON valid, JS syntax ok, ubus↔ACL совпадают | ✅ (не гонялось вживую) |
| Data-plane (nft tproxy + policy routing) | перехват TCP+UDP, loop-guard, mgmt-bypass | **на реальном ядре VM: счётчики растут, xray принимает/выпускает, SSH жив; реальный LAN-клиент (netns/veth в br-lan) перехвачен** | ✅ |
| CI/feed | gh-action-sdk матрица (x86_64/aarch64_cortex-a53/+2), подписанный фид | YAML валиден | ✅ (не запускалось) |
| examples | полный+минимальный `/etc/config/xray`, share-link фикстуры | сверено с контрактом | ✅ |
| examples | полный+минимальный `/etc/config/shater`, share-link фикстуры | сверено с контрактом | ✅ |
## Баги, найденные и починенные при верификации (реальным xray)
1. **Правило без матчеров** → `xray: this rule has no effective fields`. Фикс: catch-all
+1 -1
View File
@@ -196,7 +196,7 @@
</div>
<div class="lane ctrl"><div class="lane-h">Control plane — xrayctl (Go)</div>
<div class="row">
<div class="node ctrl"><div class="t">UCI model</div><div class="d">/etc/config/xray → 8 objects</div></div>
<div class="node ctrl"><div class="t">UCI model</div><div class="d">/etc/config/shater → 8 objects</div></div>
<div class="node ctrl"><div class="t">sub fetch + parse</div><div class="d">libXray share-links · HAPP headers</div></div>
<div class="node ctrl"><div class="t">config generator</div><div class="d">build xray JSON + nft + ip-rules</div></div>
<div class="node ctrl"><div class="t">reconciler</div><div class="d">atomic apply · validate · rollback</div></div>
+2 -2
View File
@@ -4,7 +4,7 @@
# uci-defaults). Arg $1 = output dir.
set -e
OUT="$(mkdir -p "${1:?output dir required}" && cd "$1" && pwd)"
REL="0.1.0-r1"
REL="0.1.0-r3"
W="$(mktemp -d)"; mkdir -p "$W/data" "$W/control"
cp -a shater-core/files/. "$W/data/"
@@ -21,7 +21,7 @@ Installed-Size: ${isize}
Maintainer: shater
Description: shater data-plane glue (procd init, nft tproxy via xrayctl, policy routing, DNS, sysctl).
EOF
printf '/etc/config/xray\n' > "$W/control/conffiles"
printf '/etc/config/shater\n' > "$W/control/conffiles"
cat > "$W/control/postinst" <<'EOF'
#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] && exit 0
+1 -1
View File
@@ -3,7 +3,7 @@
# no luci-base compilation. Runs on the CI runner. Arg $1 = output dir.
set -e
OUT="$(mkdir -p "${1:?output dir required}" && cd "$1" && pwd)"
REL="0.1.0-r2"
REL="0.1.0-r3"
W="$(mktemp -d)"; mkdir -p "$W/data" "$W/control"
cp -a luci-app-shater/root/. "$W/data/"
+41
View File
@@ -0,0 +1,41 @@
#!/bin/bash
# Pack a prebuilt xrayctl binary into an .ipk (no SDK). Mirrors xrayctl/Makefile
# metadata. This is used for fast local testbed iteration; CI proper builds it
# through the OpenWrt SDK (ci/build-sdk.sh). Args: $1 = binary path, $2 = arch,
# $3 = output dir.
set -e
BIN="${1:?binary path required}"
ARCH="${2:?arch required (e.g. x86_64)}"
OUT="$(mkdir -p "${3:?output dir required}" && cd "$3" && pwd)"
REL="0.1.0-r3"
W="$(mktemp -d)"; mkdir -p "$W/data/usr/bin" "$W/control"
cp "$BIN" "$W/data/usr/bin/xrayctl"
chmod 0755 "$W/data/usr/bin/xrayctl"
isize=$(du -sk "$W/data" | cut -f1)
cat > "$W/control/control" <<EOF
Package: xrayctl
Version: ${REL}
Depends: ca-bundle
Section: net
Architecture: ${ARCH}
Installed-Size: ${isize}
Maintainer: shater
Description: xray control-plane (UCI -> xray JSON + nft + policy-routing).
EOF
# Guarantee the exec bit regardless of the host tar's mode handling (msys/Windows
# tar does not always preserve 0755 in the archive), so opkg installs a runnable
# binary on the device.
cat > "$W/control/postinst" <<'EOF'
#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] || chmod 0755 /usr/bin/xrayctl
exit 0
EOF
chmod 0755 "$W/control/postinst"
echo "2.0" > "$W/debian-binary"
( cd "$W/control" && tar --numeric-owner --owner=0 --group=0 -czf ../control.tar.gz ./control ./postinst )
( cd "$W/data" && tar --numeric-owner --owner=0 --group=0 -czf ../data.tar.gz . )
( cd "$W" && tar --numeric-owner --owner=0 --group=0 -czf "$OUT/xrayctl_${REL}_${ARCH}.ipk" ./debian-binary ./data.tar.gz ./control.tar.gz )
echo "built $OUT/xrayctl_${REL}_${ARCH}.ipk"
+4 -4
View File
@@ -10,8 +10,8 @@ any field the contract left ambiguous is flagged in
| File | What it is |
|------|-----------|
| `etc-config-xray.full` | Complete `/etc/config/xray` exercising **every** section type in the contract: `globals`, multi-LAN `inbound`, two `subscription` (HAPP auto-hwid + fixed-hwid with extra headers), manual `node`, subscription- and manual-sourced `group`, a 3-hop `chain`, `egress` of all four types (interface/proxy/direct/block), `ruleset` (domain-from-url + inline ipcidr), `rule` (per-client /32, MAC, domain-list, geosite, egress binding, kill modes), `resolver` (doh+detour / local / fakeip / default) with `dns_rule`, and a WAN-mode `profile`. Generalizes the real BPi-R3 Mini setup (see `../01-mini_router-audit.md`). |
| `etc-config-xray.minimal` | Smallest useful config: one subscription, one group, one tproxy inbound, one default rule → group. For quick starts. |
| `etc-config-shater.full` | Complete `/etc/config/shater` exercising **every** section type in the contract: `globals`, multi-LAN `inbound`, two `subscription` (HAPP auto-hwid + fixed-hwid with extra headers), manual `node`, subscription- and manual-sourced `group`, a 3-hop `chain`, `egress` of all four types (interface/proxy/direct/block), `ruleset` (domain-from-url + inline ipcidr), `rule` (per-client /32, MAC, domain-list, geosite, egress binding, kill modes), `resolver` (doh+detour / local / fakeip / default) with `dns_rule`, and a WAN-mode `profile`. Generalizes the real BPi-R3 Mini setup (see `../01-mini_router-audit.md`). |
| `etc-config-shater.minimal` | Smallest useful config: one subscription, one group, one tproxy inbound, one default rule → group. For quick starts. |
| `sublinks.txt` | Mixed share-link list (one per line) covering vless+reality+vision(tcp), vless+xhttp+tls, vless+ws+tls, vmess+ws, trojan+grpc, and shadowsocks (aes-256-gcm + 2022-blake3). Structurally valid, fake values. Parser fixture. |
| `README.md` | This file. |
@@ -21,14 +21,14 @@ Render a config to xray JSON (no apply), validate, then apply:
```sh
# On the router, install one of the sample configs:
cp examples/etc-config-xray.minimal /etc/config/xray
cp examples/etc-config-shater.minimal /etc/config/shater
xrayctl test # gen + `xray -test`
xrayctl apply # gen -> test -> atomic swap (xray + nft + routing)
# or, with auto-rollback if you don't confirm within globals.confirm_timeout:
xrayctl apply --confirm 120 && xrayctl confirm
# Full-feature reference config:
cp examples/etc-config-xray.full /etc/config/xray && xrayctl test
cp examples/etc-config-shater.full /etc/config/shater && xrayctl test
```
Parse the share-link fixture (does not touch device state):
@@ -1,6 +1,6 @@
#
# =============================================================================
# /etc/config/xray -- FULL annotated example (shater / xrayctl control-plane)
# /etc/config/shater -- FULL annotated example (shater / xrayctl control-plane)
# =============================================================================
#
# This file is the DESIRED STATE. It is edited by LuCI or by hand. `xrayctl`
@@ -1,12 +1,12 @@
#
# =============================================================================
# /etc/config/xray -- MINIMAL quick-start example (shater / xrayctl)
# /etc/config/shater -- MINIMAL quick-start example (shater / xrayctl)
# =============================================================================
#
# The smallest useful config: ONE subscription, ONE group, ONE tproxy inbound,
# ONE default rule sending everything to the group. Copy to the device and
# apply:
# cp examples/etc-config-xray.minimal /etc/config/xray
# cp examples/etc-config-xray.minimal /etc/config/shater
# xrayctl test && xrayctl apply
#
# From here, add rules/chains/egresses incrementally (see etc-config-xray.full).
@@ -7,21 +7,21 @@
// group or a node as "group:<name>" / "node:<name>". Order of the list = layer order.
return view.extend({
load: function() {
return uci.load('xray');
return uci.load('shater');
},
render: function() {
var m, s, o;
// Suggestions for the hop combobox: every group and node by name.
var groups = uci.sections('xray', 'group')
var groups = uci.sections('shater', 'group')
.map(function(g) { return g.name; })
.filter(function(n) { return n != null && n !== ''; });
var nodes = uci.sections('xray', 'node')
var nodes = uci.sections('shater', 'node')
.map(function(n) { return n.name; })
.filter(function(n) { return n != null && n !== ''; });
m = new form.Map('xray', _('Shater — Chains'),
m = new form.Map('shater', _('Shater — Chains'),
_('Multi-hop chains. Each hop is a layer (L1..Ln); traffic traverses ' +
'them in list order. A hop references a group or a fixed node.'));
@@ -7,17 +7,17 @@
// + the DNS-related globals (mode, default & fallback resolver).
return view.extend({
load: function() {
return uci.load('xray');
return uci.load('shater');
},
render: function() {
var m, s, o;
var resolverNames = uci.sections('xray', 'resolver')
var resolverNames = uci.sections('shater', 'resolver')
.map(function(sec) { return sec.name; })
.filter(function(n) { return n != null && n !== ''; });
m = new form.Map('xray', _('Shater — DNS'),
m = new form.Map('shater', _('Shater — DNS'),
_('Named resolvers, per-domain / per-client DNS routing and the default ' +
'DNS behaviour. Split-DNS keeps resolved == routed to avoid leaks.'));
@@ -9,7 +9,7 @@
return view.extend({
load: function() {
return Promise.all([
uci.load('xray'),
uci.load('shater'),
network.getNetworks()
]);
},
@@ -24,7 +24,7 @@ return view.extend({
// Proxy targets we can resolve by name.
function names(type, prefix) {
return uci.sections('xray', type)
return uci.sections('shater', type)
.map(function(sec) { return sec.name; })
.filter(function(n) { return n != null && n !== ''; })
.map(function(n) { return prefix + ':' + n; });
@@ -33,7 +33,7 @@ return view.extend({
.concat(names('group', 'group'))
.concat(names('node', 'node'));
m = new form.Map('xray', _('Shater — Egress'),
m = new form.Map('shater', _('Shater — Egress'),
_('Egress points bind a route to a final exit: a network interface / ' +
'tunnel, a proxy (chain/group/node), or direct/block.'));
@@ -4,21 +4,21 @@
'require uci';
// Groups (config group) — balancers over subscription/manual node sets.
// Full CRUD against /etc/config/xray. Save commits UCI; apply from Overview.
// Full CRUD against /etc/config/shater. Save commits UCI; apply from Overview.
return view.extend({
load: function() {
return uci.load('xray');
return uci.load('shater');
},
render: function() {
var m, s, o;
// Collect subscription names for the reference dropdown.
var subNames = uci.sections('xray', 'subscription')
var subNames = uci.sections('shater', 'subscription')
.map(function(sec) { return sec.name; })
.filter(function(n) { return n != null && n !== ''; });
m = new form.Map('xray', _('Shater — Groups'),
m = new form.Map('shater', _('Shater — Groups'),
_('Groups are balancers over a set of nodes — either the whole of a ' +
'subscription or a manual list. Strategy picks how a node is chosen.'));
@@ -8,7 +8,7 @@ return view.extend({
render: function() {
var m, s, o;
m = new form.Map('xray', _('Shater — Lists / Rulesets'),
m = new form.Map('shater', _('Shater — Lists / Rulesets'),
_('Reusable, typed lists of domains or IP-CIDRs. Reference them from ' +
'rules (Dest ruleset) or DNS rules. Sourced inline, from a file, or a URL.'));
@@ -168,7 +168,7 @@ return view.extend({
]);
// --- Manual nodes CRUD (config node) ---
var m = new form.Map('xray', null,
var m = new form.Map('shater', null,
_('Manually added nodes. Each is a single share-link URI; xrayctl parses it.'));
var s = m.section(form.GridSection, 'node', _('Manual nodes'));
@@ -16,13 +16,13 @@ var callExplain = rpc.declare({
// Reference names of a UCI type as "prefix:name".
function prefixed(type, prefix) {
return uci.sections('xray', type)
return uci.sections('shater', type)
.map(function(sec) { return sec.name; })
.filter(function(n) { return n != null && n !== ''; })
.map(function(n) { return prefix + ':' + n; });
}
function nameList(type) {
return uci.sections('xray', type)
return uci.sections('shater', type)
.map(function(sec) { return sec.name; })
.filter(function(n) { return n != null && n !== ''; });
}
@@ -103,11 +103,11 @@ function renderPolicyHelper(rerender) {
ui.addNotification(null, E('p', {}, _('Pick a target (define groups/chains first).')), 'warning');
return;
}
var sid = uci.add('xray', 'rule');
uci.set('xray', sid, 'name', 'policy-' + dev.replace(/[^a-zA-Z0-9]+/g, '-'));
uci.set('xray', sid, 'enabled', '1');
uci.set('xray', sid, 'src', [ dev ]);
uci.set('xray', sid, 'target', tgt);
var sid = uci.add('shater', 'rule');
uci.set('shater', sid, 'name', 'policy-' + dev.replace(/[^a-zA-Z0-9]+/g, '-'));
uci.set('shater', sid, 'enabled', '1');
uci.set('shater', sid, 'src', [ dev ]);
uci.set('shater', sid, 'target', tgt);
devIn.value = '';
ui.addNotification(null, E('p', {},
_('Rule added below — review, then Save & Apply.')), 'info');
@@ -131,7 +131,7 @@ function renderPolicyHelper(rerender) {
return view.extend({
load: function() {
return uci.load('xray');
return uci.load('shater');
},
render: function() {
@@ -143,7 +143,7 @@ return view.extend({
var egresses = nameList('egress');
var rulesets = nameList('ruleset');
m = new form.Map('xray', _('Shater — Rules'),
m = new form.Map('shater', _('Shater — Rules'),
_('Ordered routing rules (first match wins). Complex match lists are edited in the row dialog.'));
s = m.section(form.GridSection, 'rule', _('Rules'));
@@ -2,16 +2,16 @@
'require view';
'require form';
// Global settings + inbounds (multi-LAN tproxy), backed by /etc/config/xray.
// Global settings + inbounds (multi-LAN tproxy), backed by /etc/config/shater.
// DNS resolvers / rules moved to the dedicated DNS page.
// Save & Apply commits UCI; use Overview -> Apply to render+apply via xrayctl.
return view.extend({
render: function() {
var m, s, o;
m = new form.Map('xray', _('Shater — Settings'),
m = new form.Map('shater', _('Shater — Settings'),
_('Global engine options and transparent-proxy inbounds. DNS is on its own page. ' +
'Saving commits /etc/config/xray; apply the running config from the Overview page.'));
'Saving commits /etc/config/shater; apply the running config from the Overview page.'));
// ---------------- globals ----------------
s = m.section(form.NamedSection, 'globals', 'globals', _('Global'));
@@ -23,7 +23,7 @@ return view.extend({
render: function() {
var m, s, o;
m = new form.Map('xray', _('Shater — Subscriptions'),
m = new form.Map('shater', _('Shater — Subscriptions'),
_('Remote node subscriptions with HAPP-style header emulation. ' +
'Each subscription has its own update interval; use "Update now" to refresh immediately.'));
@@ -91,7 +91,7 @@ return view.extend({
o.inputstyle = 'apply';
o.modalonly = false;
o.onclick = function(ev, section_id) {
var name = uci.get('xray', section_id, 'name') || '';
var name = uci.get('shater', section_id, 'name') || '';
return callSubUpdate(name).then(updateNotify);
};
@@ -1,6 +1,6 @@
#!/bin/sh
# luci-app-shater first-boot hook.
# The default /etc/config/xray is shipped/seeded by shater-core, NOT here.
# The default /etc/config/shater is shipped/seeded by shater-core, NOT here.
# We only clear the LuCI caches so the new menu/views appear.
rm -f /tmp/luci-indexcache*
rm -rf /tmp/luci-modulecache/
@@ -2,13 +2,13 @@
"luci-app-shater": {
"description": "Grant UCI and ubus access to luci-app-shater (xray control plane)",
"read": {
"uci": [ "xray" ],
"uci": [ "shater" ],
"ubus": {
"xray": [ "status", "nodes", "stats", "explain" ]
}
},
"write": {
"uci": [ "xray" ],
"uci": [ "shater" ],
"ubus": {
"xray": [ "sub_update", "apply", "confirm", "reload", "node_test", "node_import" ]
}
+4 -4
View File
@@ -14,7 +14,7 @@ include $(TOPDIR)/rules.mk
PKG_NAME:=shater-core
PKG_VERSION:=0.1.0
PKG_RELEASE:=1
PKG_RELEASE:=3
PKG_MAINTAINER:=Shater <maqrota@icloud.com>
PKG_LICENSE:=GPL-2.0-or-later
@@ -45,9 +45,9 @@ define Package/shater-core/description
enabled and a generated runtime config exists.
endef
# /etc/config/xray is user-editable desired state -> preserve on upgrade.
# /etc/config/shater is user-editable desired state -> preserve on upgrade.
define Package/shater-core/conffiles
/etc/config/xray
/etc/config/shater
endef
# Nothing to fetch or build.
@@ -70,7 +70,7 @@ define Package/shater-core/install
$(INSTALL_DATA) ./files/etc/sysctl.d/99-shater.conf $(1)/etc/sysctl.d/99-shater.conf
$(INSTALL_DIR) $(1)/etc/config
$(INSTALL_CONF) ./files/etc/config/xray $(1)/etc/config/xray
$(INSTALL_CONF) ./files/etc/config/shater $(1)/etc/config/shater
$(INSTALL_DIR) $(1)/etc/uci-defaults
$(INSTALL_BIN) ./files/etc/uci-defaults/30_shater-core $(1)/etc/uci-defaults/30_shater-core
@@ -1,5 +1,5 @@
#
# Shater desired-state config (/etc/config/xray).
# Shater desired-state config (/etc/config/shater).
#
# This shipped default is intentionally INERT: globals.enabled='0' means the
# init script opens no instance and touches nothing, so a fresh install cannot
@@ -16,7 +16,7 @@ case "$ACTION" in
esac
# Only act when explicitly enabled.
en=$(uci -q get xray.globals.enabled) || exit 0
en=$(uci -q get shater.globals.enabled) || exit 0
[ "$en" = "1" ] || exit 0
/usr/bin/xrayctl reconcile >/dev/null 2>&1
+12 -8
View File
@@ -21,7 +21,7 @@ STOP=10
PROG=/usr/bin/xray
XRAYCTL=/usr/bin/xrayctl
RUN_JSON=/etc/xray/run.json
UCI_CONF=/etc/config/xray
UCI_CONF=/etc/config/shater
RUN_DIR=/var/run/xray
PID_FILE=/var/run/xray/xray.pid
ASSET_DIR=/usr/share/xray
@@ -31,7 +31,7 @@ ASSET_DIR=/usr/share/xray
# True only when the stack is explicitly enabled in UCI.
shater_enabled() {
local en
en=$(uci -q get xray.globals.enabled) || return 1
en=$(uci -q get shater.globals.enabled) || return 1
[ "$en" = "1" ]
}
@@ -54,7 +54,7 @@ shater_teardown() {
# Policy routing in our reserved table block. We only clear tables at/above
# table_base, never the main/default/local tables or fw4 state.
local tbase base t
tbase=$(uci -q get xray.globals.table_base)
tbase=$(uci -q get shater.globals.table_base)
[ -n "$tbase" ] || tbase="0x2000"
base=$(shater_to_dec "$tbase") || return 0
[ -n "$base" ] || return 0
@@ -118,11 +118,15 @@ stop_service() {
}
reload_service() {
# UCI changed. Regeneration + atomic apply of run.json is xrayctl's job
# (invoked from LuCI/ubus); here we reconcile the kernel and let procd
# restart xray if run.json changed. If the stack was disabled, tear down.
# Fired by the `shater` config.change reload-trigger. `start` re-runs
# start_service, which regenerates run.json + reconciles nft/routing (a single
# `xrayctl reconcile`); procd's file-watch then restarts xray if run.json
# changed. When the stack is disabled we tear our resources down. We must NOT
# call `shater_reconcile` in addition to `start` — that would run reconcile
# twice per reload (a second, needless `xray -test`), and any path that makes
# `xrayctl reconcile` itself invoke `/etc/init.d/shater reload` would turn this
# into an unbounded fork storm.
if shater_enabled; then
shater_reconcile
start
else
stop
@@ -130,5 +134,5 @@ reload_service() {
}
service_triggers() {
procd_add_reload_trigger "xray"
procd_add_reload_trigger "shater"
}
+11 -11
View File
@@ -35,7 +35,7 @@ DEFAULT_RS_INTERVAL=24h
shater_enabled() {
local en
en=$(uci -q get xray.globals.enabled) || return 1
en=$(uci -q get shater.globals.enabled) || return 1
[ "$en" = "1" ]
}
@@ -74,12 +74,12 @@ shater_run_due() {
# Subscriptions.
i=0
while uci -q get "xray.@subscription[$i]" >/dev/null 2>&1; do
name=$(uci -q get "xray.@subscription[$i].name")
en=$(uci -q get "xray.@subscription[$i].enabled")
while uci -q get "shater.@subscription[$i]" >/dev/null 2>&1; do
name=$(uci -q get "shater.@subscription[$i].name")
en=$(uci -q get "shater.@subscription[$i].enabled")
[ -z "$en" ] && en=1
if [ -n "$name" ] && [ "$en" = "1" ]; then
ivl=$(uci -q get "xray.@subscription[$i].update_interval")
ivl=$(uci -q get "shater.@subscription[$i].update_interval")
secs=$(shater_ivl_secs "$ivl" "$DEFAULT_SUB_INTERVAL")
stamp="$STAMP_DIR/sub.$name"
if shater_due "$stamp" "$secs"; then
@@ -93,11 +93,11 @@ shater_run_due() {
# Rulesets (only url sources auto-update; others have nothing to fetch).
i=0
while uci -q get "xray.@ruleset[$i]" >/dev/null 2>&1; do
name=$(uci -q get "xray.@ruleset[$i].name")
src=$(uci -q get "xray.@ruleset[$i].source")
while uci -q get "shater.@ruleset[$i]" >/dev/null 2>&1; do
name=$(uci -q get "shater.@ruleset[$i].name")
src=$(uci -q get "shater.@ruleset[$i].source")
if [ -n "$name" ] && [ "$src" = "url" ]; then
ivl=$(uci -q get "xray.@ruleset[$i].update_interval")
ivl=$(uci -q get "shater.@ruleset[$i].update_interval")
secs=$(shater_ivl_secs "$ivl" "$DEFAULT_RS_INTERVAL")
stamp="$STAMP_DIR/rs.$name"
if shater_due "$stamp" "$secs"; then
@@ -135,7 +135,7 @@ start_service() {
# Re-exec ourselves as the loop body so procd supervises a single process.
procd_set_param command /bin/sh "$INIT_SCRIPT" loop
procd_set_param respawn 3600 10 0 # threshold timeout always-retry
procd_set_param file /etc/config/xray # restart the loop when UCI changes
procd_set_param file /etc/config/shater # restart the loop when UCI changes
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
@@ -149,5 +149,5 @@ reload_service() {
}
service_triggers() {
procd_add_reload_trigger "xray"
procd_add_reload_trigger "shater"
}
+2 -2
View File
@@ -24,7 +24,7 @@ Files installed
src_valid_mark=1 (+ IPv6 forwarding) — required for TPROXY + the
`local ... dev lo` policy-routing trick.
/etc/config/xray
/etc/config/shater
Minimal INERT UCI default (globals.enabled='0'). Installed as a conffile:
your edits survive upgrades. Full schema in CONTRACT.md.
@@ -52,7 +52,7 @@ Runtime layout (created/managed by xrayctl, for reference)
Operating
---------
Configure via LuCI or `uci set xray.globals.enabled=1` then apply:
Configure via LuCI or `uci set shater.globals.enabled=1` then apply:
xrayctl apply # gen -> test -> atomic apply (+ optional confirm)
/etc/init.d/shater start # or restart; reconcile runs automatically
Inspect:
+1 -1
View File
@@ -10,7 +10,7 @@ include $(TOPDIR)/rules.mk
PKG_NAME:=xrayctl
PKG_VERSION:=0.1.0
PKG_RELEASE:=2
PKG_RELEASE:=3
PKG_MAINTAINER:=shater
PKG_LICENSE:=MIT
+20 -7
View File
@@ -211,9 +211,14 @@ func Reconcile() error {
if err := writeJSON(runJSON, cfg); err != nil {
return err
}
if err := reloadXray(); err != nil {
return err
}
// Do NOT poke the init script here. Reconcile is invoked FROM the shater
// service lifecycle (start_service / reload_service / service_started /
// hotplug / watchdog); calling `/etc/init.d/shater reload` back would re-enter
// reload_service -> shater_reconcile -> Reconcile -> ... an unbounded fork
// storm that OOMs the box. procd already restarts xray via its file-watch on
// run.json (`procd_set_param file $RUN_JSON`), so writing run.json above is
// sufficient to pick up the new engine config.
//
// Drift detection: re-apply nft/routing when our resources are missing, and
// always ensure they are present (idempotent — delete-then-add semantics).
if err := applyNft(m); err != nil {
@@ -235,12 +240,20 @@ func apDrifted(m *Model) bool {
func reloadXray() error {
// Our procd service /etc/init.d/shater runs `xray run -c /etc/xray/run.json`
// (with a file-watch on run.json). Reloading it restarts xray with the freshly
// written run.json. The stock xray-core service is NOT ours (different schema),
// with a file-watch on run.json (`procd_set_param file $RUN_JSON`). Callers
// (Apply/Rollback) have already written the fresh run.json, so:
// * if the service is already up, procd's file-watch restarts xray with the
// new config on its own — `start` is then a cheap no-op;
// * if it is inert (first apply / was stopped), `start` brings it up.
//
// We deliberately use `start`, NOT `reload`. `reload` re-enters the init's
// reload_service -> shater_reconcile -> `xrayctl reconcile` -> Reconcile(); and
// only Apply/Rollback call this function (never the init lifecycle), so `start`
// cannot recurse. The stock xray-core service is NOT ours (different schema),
// so we must never poke `service xray`.
if _, err := os.Stat("/etc/init.d/shater"); err == nil {
if out, err := exec.Command("/etc/init.d/shater", "reload").CombinedOutput(); err != nil {
return fmt.Errorf("shater reload: %v\n%s", err, out)
if out, err := exec.Command("/etc/init.d/shater", "start").CombinedOutput(); err != nil {
return fmt.Errorf("shater start: %v\n%s", err, out)
}
return nil
}
+1 -1
View File
@@ -1,7 +1,7 @@
package main
// Data model for the xray control-plane. This is the parsed, typed form of the
// UCI desired-state (/etc/config/xray) plus subscription-cache nodes. Every
// UCI desired-state (/etc/config/shater) plus subscription-cache nodes. Every
// generator/apply step consumes *Model; nothing downstream touches raw UCI.
import (
+5 -5
View File
@@ -599,25 +599,25 @@ func subAddNodesUCI(nodes []CachedNode) (int, error) {
used := subExistingNodeNames()
added := 0
for _, nd := range nodes {
out, err := exec.Command("uci", "add", "xray", "node").Output()
out, err := exec.Command("uci", "add", "shater", "node").Output()
if err != nil {
return added, fmt.Errorf("uci add node: %w", err)
}
id := strings.TrimSpace(string(out))
name := subUniqueName(sanitize(nd.Name), used)
used[name] = true
if err := exec.Command("uci", "set", "xray."+id+".name="+name).Run(); err != nil {
if err := exec.Command("uci", "set", "shater."+id+".name="+name).Run(); err != nil {
return added, err
}
if err := exec.Command("uci", "set", "xray."+id+".uri="+nd.URI).Run(); err != nil {
if err := exec.Command("uci", "set", "shater."+id+".uri="+nd.URI).Run(); err != nil {
return added, err
}
if err := exec.Command("uci", "set", "xray."+id+".enabled=1").Run(); err != nil {
if err := exec.Command("uci", "set", "shater."+id+".enabled=1").Run(); err != nil {
return added, err
}
added++
}
if err := exec.Command("uci", "commit", "xray").Run(); err != nil {
if err := exec.Command("uci", "commit", "shater").Run(); err != nil {
return added, fmt.Errorf("uci commit: %w", err)
}
return added, nil
+4 -4
View File
@@ -1,6 +1,6 @@
package main
// UCI ingestion. On a device we shell out to `uci -q export xray`; the export
// UCI ingestion. On a device we shell out to `uci -q export shater`; the export
// format (package/config/option/list) is parsed by a pure function so the whole
// mapping is unit-testable from a string fixture.
@@ -19,11 +19,11 @@ type uciSection struct {
Lists map[string][]string
}
// ReadUCI runs `uci -q export xray` and parses it into a Model.
// ReadUCI runs `uci -q export shater` and parses it into a Model.
func ReadUCI() (*Model, error) {
out, err := exec.Command("uci", "-q", "export", "xray").Output()
out, err := exec.Command("uci", "-q", "export", "shater").Output()
if err != nil {
return nil, fmt.Errorf("uci export xray: %w", err)
return nil, fmt.Errorf("uci export shater: %w", err)
}
return ParseUCIExport(string(out))
}