feat(core): fail-safe hardening — live-flag, watchdog, procd fixes
Close the "rules live, engine dead" LAN-blackout class and make an admin `stop` durable: - live-flag /var/run/shater.active gates hotplug/cron reconcile, so `stop` sticks — a WAN flap can no longer resurrect interception behind a stopped engine. - procd respawn retry=0 (never abandon the engine while rules stand) + guard that /usr/bin/xray is executable before installing the data plane. - shater-cron watchdog: engine dead N ticks with interception live escalates per kill_switch (open -> auto-stop/fail-open, closed -> crit log). - fix procd cron detach: `command "$INIT_SCRIPT" loop` (rc.common dispatch) instead of `/bin/sh $INIT_SCRIPT loop`, which detached the loop from procd (running:false + respawn churn) — the auto-updater/watchdog ran unsupervised. - run.json regenerated at start after sysupgrade; cron stamps only on success with backoff, and waits for a default route before boot-time fetches. - sysctl route_localnet/accept_local scoped to lo (was all — WAN anti-spoof weakening); applied at install time so no reboot is needed. - fix stale example filenames; bump shater-core to r19. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LLthkP2S8WAfxu7fcYbPfE
This commit is contained in:
1 parent
f1e4f16a9f
commit
65883e20d9
8 files changed
+260
-72
No files matched your search
@@ -27,3 +27,6 @@ Thumbs.db
|
||||
NUL
|
||||
nul
|
||||
out/
|
||||
|
||||
# playwright MCP screenshots/snapshots
|
||||
.playwright-mcp/
|
||||
@@ -6,10 +6,10 @@
|
||||
# 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/shater
|
||||
# cp examples/etc-config-shater.minimal /etc/config/shater
|
||||
# xrayctl test && xrayctl apply
|
||||
#
|
||||
# From here, add rules/chains/egresses incrementally (see etc-config-xray.full).
|
||||
# From here, add rules/chains/egresses incrementally (see etc-config-shater.full).
|
||||
# =============================================================================
|
||||
|
||||
config globals 'globals'
|
||||
|
||||
@@ -14,7 +14,7 @@ include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=shater-core
|
||||
PKG_VERSION:=0.1.0
|
||||
PKG_RELEASE:=17
|
||||
PKG_RELEASE:=19
|
||||
|
||||
PKG_MAINTAINER:=Shater <maqrota@icloud.com>
|
||||
PKG_LICENSE:=GPL-2.0-or-later
|
||||
|
||||
@@ -3,10 +3,13 @@
|
||||
#
|
||||
# netifd wipes `ip rule` / `ip route` on `network reload` and on interface
|
||||
# churn, so our policy routing must be re-persisted on every ifup/ifdown.
|
||||
# xrayctl reconcile is idempotent, so re-running it here is safe and cheap.
|
||||
# xrayctl reconcile is idempotent (flock-serialized, hash-compared), so
|
||||
# re-running it here is safe and cheap.
|
||||
#
|
||||
# Fully inert unless the Shater stack is enabled — never disturbs connectivity
|
||||
# on boxes where the package is merely installed.
|
||||
# Fully inert unless the Shater stack is enabled AND the main service is live
|
||||
# (ACTIVE_FLAG raised by /etc/init.d/shater start, cleared by stop). Guarding
|
||||
# on the flag — not just on UCI — means an admin `stop` sticks: a WAN flap can
|
||||
# never resurrect interception behind a deliberately stopped engine.
|
||||
|
||||
[ -x /usr/bin/xrayctl ] || exit 0
|
||||
|
||||
@@ -15,9 +18,22 @@ case "$ACTION" in
|
||||
*) exit 0 ;;
|
||||
esac
|
||||
|
||||
# Only act when explicitly enabled.
|
||||
# Only act when explicitly enabled AND the service is meant to be running.
|
||||
en=$(uci -q get shater.globals.enabled) || exit 0
|
||||
[ "$en" = "1" ] || exit 0
|
||||
[ -f /var/run/shater.active ] || exit 0
|
||||
|
||||
# Coalesce interface-flap storms: each reconcile runs a full `xray -test`,
|
||||
# which is real CPU on small routers. The FIRST event in a burst schedules one
|
||||
# reconcile 2s out (absorbing the burst's rule-wipes); followers in that window
|
||||
# exit — their wipes are covered by the pending pass. The marker is released
|
||||
# BEFORE reconciling so an event landing mid-reconcile schedules a fresh pass
|
||||
# and no wipe is ever left unrepaired.
|
||||
pending=/var/run/shater/hotplug.pending
|
||||
mkdir -p /var/run/shater
|
||||
mkdir "$pending" 2>/dev/null || exit 0
|
||||
sleep 2
|
||||
rmdir "$pending" 2>/dev/null
|
||||
|
||||
/usr/bin/xrayctl reconcile >/dev/null 2>&1
|
||||
|
||||
|
||||
@@ -6,9 +6,16 @@
|
||||
# policy routing (ip rules/routes in our reserved table base) and our nft table.
|
||||
#
|
||||
# RELIABILITY CONTRACT (the "железно" layer):
|
||||
# * Completely INERT unless globals.enabled=1 AND /etc/xray/run.json exists.
|
||||
# On a fresh/misconfigured box start_service exits cleanly with no instance
|
||||
# and no data-plane changes, so boot connectivity is NEVER affected.
|
||||
# * Completely INERT unless globals.enabled=1. On a fresh/misconfigured box
|
||||
# start_service exits cleanly with no instance and no data-plane changes,
|
||||
# so boot connectivity is NEVER affected.
|
||||
# * The interception data plane may only exist while this service is meant to
|
||||
# be running. `start` raises ACTIVE_FLAG, `stop` clears it AND tears the
|
||||
# data plane down; hotplug/cron reconcile ONLY while the flag is up, so an
|
||||
# admin `stop` STICKS — no background actor may resurrect interception.
|
||||
# * The engine must never be permanently abandoned while interception stands:
|
||||
# respawn retries are infinite (procd never gives up); a sustained-dead
|
||||
# engine is additionally escalated by the shater-cron watchdog.
|
||||
# * Teardown only ever touches OUR resources: nft table `inet shater` and the
|
||||
# routing tables in the reserved base (default 0x2000). fw4's table and the
|
||||
# management/LAN paths are never touched.
|
||||
@@ -21,10 +28,13 @@ STOP=10
|
||||
PROG=/usr/bin/xray
|
||||
XRAYCTL=/usr/bin/xrayctl
|
||||
RUN_JSON=/etc/xray/run.json
|
||||
UCI_CONF=/etc/config/shater
|
||||
RUN_DIR=/var/run/xray
|
||||
PID_FILE=/var/run/xray/xray.pid
|
||||
ASSET_DIR=/usr/share/xray
|
||||
# Raised while the service is meant to be running; the ONLY token that lets
|
||||
# hotplug/shater-cron touch the data plane. tmpfs => cleared by reboot, so
|
||||
# nothing reconciles before this init has run at boot.
|
||||
ACTIVE_FLAG=/var/run/shater.active
|
||||
|
||||
# --- helpers ---------------------------------------------------------------
|
||||
|
||||
@@ -36,11 +46,22 @@ shater_enabled() {
|
||||
}
|
||||
|
||||
# Normalize a UCI numeric option (hex "0x2000" or decimal "8192") to decimal.
|
||||
# Rejects anything that is not a clean hex/decimal literal — a malformed value
|
||||
# must NOT silently disable teardown (the caller falls back to the default).
|
||||
shater_to_dec() {
|
||||
case "$1" in
|
||||
0x*|0X*|[0-9]*) echo $(( $1 )) ;;
|
||||
*) return 1 ;;
|
||||
local v="$1" rest
|
||||
case "$v" in
|
||||
0x*|0X*)
|
||||
rest="${v#0[xX]}"
|
||||
[ -n "$rest" ] || return 1
|
||||
case "$rest" in *[!0-9a-fA-F]*) return 1 ;; esac
|
||||
;;
|
||||
*)
|
||||
[ -n "$v" ] || return 1
|
||||
case "$v" in *[!0-9]*) return 1 ;; esac
|
||||
;;
|
||||
esac
|
||||
echo $(( v ))
|
||||
}
|
||||
|
||||
# Best-effort removal of OUR data-plane state. Safe to run repeatedly and when
|
||||
@@ -52,12 +73,12 @@ shater_teardown() {
|
||||
fi
|
||||
|
||||
# Policy routing in our reserved table block. We only clear tables at/above
|
||||
# table_base, never the main/default/local tables or fw4 state.
|
||||
# table_base, never the main/default/local tables or fw4 state. A malformed
|
||||
# table_base falls back to the shipped default — teardown must ALWAYS run.
|
||||
local tbase base t
|
||||
tbase=$(uci -q get shater.globals.table_base)
|
||||
[ -n "$tbase" ] || tbase="0x2000"
|
||||
base=$(shater_to_dec "$tbase") || return 0
|
||||
[ -n "$base" ] || return 0
|
||||
base=$(shater_to_dec "$tbase") || base=8192
|
||||
|
||||
t="$base"
|
||||
while [ "$t" -lt $(( base + 64 )) ]; do
|
||||
@@ -73,7 +94,8 @@ shater_teardown() {
|
||||
|
||||
# Idempotent kernel reconcile via the control-plane (routing + nft). Brings the
|
||||
# UCI schema forward first (idempotent; refuses a newer schema) so an upgraded
|
||||
# xrayctl never generates from a stale config.
|
||||
# xrayctl never generates from a stale config. xrayctl serializes itself with
|
||||
# an flock and hash-compares run.json, so re-running this is safe and cheap.
|
||||
shater_reconcile() {
|
||||
[ -x "$XRAYCTL" ] && "$XRAYCTL" migrate >/dev/null 2>&1
|
||||
[ -x "$XRAYCTL" ] && "$XRAYCTL" reconcile >/dev/null 2>&1
|
||||
@@ -83,56 +105,77 @@ shater_reconcile() {
|
||||
# --- procd lifecycle -------------------------------------------------------
|
||||
|
||||
start_service() {
|
||||
# Guard: stay inert unless enabled and a generated runtime config exists.
|
||||
# Returning with no instance opened means procd supervises nothing — the
|
||||
# box keeps forwarding traffic exactly as if this package were absent.
|
||||
# Guard: stay inert unless explicitly enabled.
|
||||
shater_enabled || return 0
|
||||
[ -f "$RUN_JSON" ] || return 0
|
||||
|
||||
# Guard: never install interception without a working engine binary. A
|
||||
# half-removed/failed xray upgrade must degrade to "plugin off", not to a
|
||||
# LAN whose traffic is diverted into nothing.
|
||||
if [ ! -x "$PROG" ]; then
|
||||
logger -t shater -p daemon.err \
|
||||
"xray binary missing/not executable at $PROG — refusing to start (LAN stays on plain routing)"
|
||||
return 0
|
||||
fi
|
||||
|
||||
mkdir -p "$RUN_DIR" "$(dirname "$RUN_JSON")"
|
||||
|
||||
# run.json is generated state (lost on sysupgrade). If it is missing but the
|
||||
# stack is enabled, regenerate it from UCI before opening the instance —
|
||||
# otherwise the box comes up enabled-but-engineless and the first background
|
||||
# reconcile would install interception with nothing listening behind it.
|
||||
if [ ! -f "$RUN_JSON" ]; then
|
||||
[ -x "$XRAYCTL" ] && "$XRAYCTL" migrate >/dev/null 2>&1
|
||||
[ -x "$XRAYCTL" ] && "$XRAYCTL" reconcile >/dev/null 2>&1
|
||||
if [ ! -f "$RUN_JSON" ]; then
|
||||
logger -t shater -p daemon.err \
|
||||
"enabled but could not generate $RUN_JSON — staying inert (check 'xrayctl reconcile' output)"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
procd_open_instance shater
|
||||
# xray runs in the FOREGROUND under procd (must never daemonize).
|
||||
procd_set_param command "$PROG" run -c "$RUN_JSON"
|
||||
procd_set_param env XRAY_LOCATION_ASSET="$ASSET_DIR" # geoip.dat/geosite.dat
|
||||
# threshold(10) timeout(2) retries(5): a low threshold means an engine that ran
|
||||
# >10s and is then restarted (xrayctl reloadXray SIGTERMs it to pick up a fresh
|
||||
# run.json without a reconcile) is respawned unconditionally — only genuine
|
||||
# <10s crash loops count toward the retry limit and eventually give up.
|
||||
procd_set_param respawn 10 2 5
|
||||
procd_set_param file "$RUN_JSON" # restart if run.json changes
|
||||
procd_set_param file "$UCI_CONF" # restart if UCI changes
|
||||
# threshold(3600) timeout(5) retries(0=INFINITE): procd must NEVER give up on
|
||||
# the engine while our interception rules stand — an abandoned engine with
|
||||
# live TPROXY+DNS-hijack rules is a permanent LAN blackout. A genuine crash
|
||||
# loop retries every 5s (cheap); sustained death is escalated by the
|
||||
# shater-cron watchdog (which fails open / alerts per kill_switch policy).
|
||||
procd_set_param respawn 3600 5 0
|
||||
# NOTE: deliberately NO `procd_set_param file` watches. run.json changes are
|
||||
# propagated by xrayctl itself (hash-compare + engine SIGTERM on real change),
|
||||
# and UCI edits flow through the reload trigger below. A file-watch here
|
||||
# would bounce the tunnel (dropping every proxied connection) on every UCI
|
||||
# commit even when the rendered config is byte-identical.
|
||||
procd_set_param stdout 1 # -> logread
|
||||
procd_set_param stderr 1
|
||||
procd_set_param term_timeout 10
|
||||
procd_set_param pidfile "$PID_FILE"
|
||||
procd_close_instance
|
||||
|
||||
# Persist policy routing / nft table for the freshly (re)started engine.
|
||||
# Mark the stack live for hotplug/cron, then persist policy routing / nft
|
||||
# for the freshly (re)started engine.
|
||||
mkdir -p "$(dirname "$ACTIVE_FLAG")"
|
||||
: > "$ACTIVE_FLAG"
|
||||
shater_reconcile
|
||||
}
|
||||
|
||||
service_started() {
|
||||
# Re-arm reconcile once procd reports the instance up (covers the case where
|
||||
# reconcile in start_service raced the listener).
|
||||
shater_enabled && shater_reconcile
|
||||
return 0
|
||||
}
|
||||
|
||||
stop_service() {
|
||||
# procd stops the xray instance itself; we only tear down our kernel state.
|
||||
# Drop the live-flag FIRST so a concurrent hotplug/cron tick cannot rebuild
|
||||
# what we are about to tear down; procd stops the xray instance itself.
|
||||
rm -f "$ACTIVE_FLAG"
|
||||
shater_teardown
|
||||
}
|
||||
|
||||
reload_service() {
|
||||
# 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.
|
||||
# start_service, which reconciles nft/routing; xrayctl's reconcile compares
|
||||
# the rendered run.json hash and restarts the engine ONLY on real change.
|
||||
# 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, 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
|
||||
start
|
||||
else
|
||||
|
||||
@@ -1,23 +1,38 @@
|
||||
#!/bin/sh /etc/rc.common
|
||||
# /etc/init.d/shater-cron — periodic auto-updater for subscriptions & rulesets.
|
||||
# /etc/init.d/shater-cron — periodic auto-updater for subscriptions & rulesets,
|
||||
# plus the data-plane watchdog.
|
||||
#
|
||||
# A tiny procd-supervised loop that, once per tick, checks every enabled
|
||||
# subscription and url-ruleset against its per-item `update_interval` and runs
|
||||
# xrayctl sub update <name> (subscriptions)
|
||||
# xrayctl ruleset update <name> (url rulesets)
|
||||
# when the item is due, then a single `xrayctl reconcile` if anything changed.
|
||||
# when the item is due, then a single `xrayctl reconcile` if anything changed
|
||||
# (xrayctl hash-compares run.json and restarts the engine only on real change).
|
||||
#
|
||||
# RELIABILITY CONTRACT (same "железно" posture as /etc/init.d/shater):
|
||||
# * Fully INERT unless globals.enabled=1 and xrayctl is present. On a fresh or
|
||||
# disabled box no instance is opened and nothing ever runs.
|
||||
# * Only ever invokes xrayctl verbs — never touches the data plane directly.
|
||||
# * The loop body is fully INERT unless globals.enabled=1 AND the main shater
|
||||
# service is live (ACTIVE_FLAG raised by its start, cleared by its stop).
|
||||
# An admin `stop` of the main service therefore STICKS — this loop idles.
|
||||
# * Only ever invokes xrayctl verbs / the shater init — never touches the
|
||||
# data plane directly.
|
||||
# * Due-ness is tracked with epoch stamp FILES under a tmpfs run dir, so no
|
||||
# dependence on `date -r`. Stamps are lost on reboot => every item is due at
|
||||
# boot, giving a fetch-at-boot exactly as the feature catalog requires.
|
||||
# * busybox ash only — no bashisms. `sh -n` clean.
|
||||
# Fetches are skipped (not stamped) while the box has no default route, so
|
||||
# the boot-time fetch actually happens once WAN is up instead of silently
|
||||
# burning the attempt.
|
||||
# * A stamp is written ONLY on success; a failed fetch is retried after a
|
||||
# short backoff (RETRY_SECS) instead of waiting out the full interval.
|
||||
# * WATCHDOG: if interception is meant to be live but the engine has been
|
||||
# dead for WATCHDOG_TICKS consecutive ticks, we escalate: with
|
||||
# kill_switch=open the main service is STOPPED (tears interception down —
|
||||
# fail-open, LAN returns to plain routing); with kill_switch=closed the
|
||||
# rules stay (blocked-by-design) and we log loudly.
|
||||
# * The loop never self-exits (procd would respawn-churn an exiting body);
|
||||
# it idles on its guards instead. busybox ash only — no bashisms.
|
||||
|
||||
USE_PROCD=1
|
||||
START=96 # after the main shater init (99) is irrelevant; loop self-guards
|
||||
START=96 # order vs the main init (99) is irrelevant; loop self-guards
|
||||
STOP=11
|
||||
|
||||
# `loop` is an internal action procd re-execs to run the periodic body.
|
||||
@@ -25,9 +40,14 @@ EXTRA_COMMANDS="loop"
|
||||
EXTRA_HELP=" loop internal: run the periodic update loop (invoked by procd)"
|
||||
|
||||
INIT_SCRIPT=/etc/init.d/shater-cron
|
||||
SHATER_INIT=/etc/init.d/shater
|
||||
XRAYCTL=/usr/bin/xrayctl
|
||||
RUN_JSON=/etc/xray/run.json
|
||||
ACTIVE_FLAG=/var/run/shater.active
|
||||
STAMP_DIR=/var/run/shater/cron
|
||||
TICK=60 # seconds between due-checks
|
||||
RETRY_SECS=300 # backoff before retrying a FAILED fetch
|
||||
WATCHDOG_TICKS=5 # consecutive dead-engine ticks before escalating
|
||||
DEFAULT_SUB_INTERVAL=6h
|
||||
DEFAULT_RS_INTERVAL=24h
|
||||
|
||||
@@ -39,14 +59,39 @@ shater_enabled() {
|
||||
[ "$en" = "1" ]
|
||||
}
|
||||
|
||||
# The main service raised its live-flag (start) and has not stopped since.
|
||||
shater_active() {
|
||||
[ -f "$ACTIVE_FLAG" ]
|
||||
}
|
||||
|
||||
# Best-effort "do we have an uplink" check; fetching before WAN is up at boot
|
||||
# would waste each item's one boot attempt.
|
||||
shater_has_uplink() {
|
||||
ip route show default 2>/dev/null | grep -q '^default' && return 0
|
||||
ip -6 route show default 2>/dev/null | grep -q '^default'
|
||||
}
|
||||
|
||||
# Stamp names embed the UCI item name; keep them to one safe path component.
|
||||
shater_safe_name() {
|
||||
echo "$1" | sed 's/[^A-Za-z0-9._-]/_/g'
|
||||
}
|
||||
|
||||
# Convert 30m|6h|24h|2d|3600 -> seconds on stdout. $2 is a fallback token used
|
||||
# when the input is empty or malformed.
|
||||
# when the input is empty or malformed (the FALLBACK is honored, not a
|
||||
# hardcoded constant).
|
||||
shater_ivl_secs() {
|
||||
local v="$1" def="$2" n u
|
||||
[ -n "$v" ] || v="$def"
|
||||
n=$(echo "$v" | sed 's/[^0-9].*$//')
|
||||
u=$(echo "$v" | sed 's/^[0-9]*//')
|
||||
if [ -z "$n" ]; then
|
||||
# Malformed (no leading digits): fall back to the caller's default; if
|
||||
# that is somehow malformed too, 6h.
|
||||
v="$def"
|
||||
n=$(echo "$v" | sed 's/[^0-9].*$//')
|
||||
u=$(echo "$v" | sed 's/^[0-9]*//')
|
||||
[ -n "$n" ] || { echo 21600; return; }
|
||||
fi
|
||||
case "$u" in
|
||||
s|"") echo "$n" ;;
|
||||
m|M) echo $(( n * 60 )) ;;
|
||||
@@ -67,6 +112,17 @@ shater_due() {
|
||||
|
||||
shater_stamp() { mkdir -p "$STAMP_DIR"; date +%s > "$1"; }
|
||||
|
||||
# Failed fetch: pretend the last success was (interval - RETRY_SECS) ago so the
|
||||
# item comes due again after a short backoff instead of a full interval — but
|
||||
# never sooner than RETRY_SECS (guards tiny intervals).
|
||||
shater_stamp_retry() {
|
||||
local stamp="$1" ivl="$2" back
|
||||
back=$(( ivl - RETRY_SECS ))
|
||||
[ "$back" -gt 0 ] || back=0
|
||||
mkdir -p "$STAMP_DIR"
|
||||
echo $(( $(date +%s) - back )) > "$stamp"
|
||||
}
|
||||
|
||||
# Walk anonymous `config subscription` / `config ruleset` sections by index and
|
||||
# run any that are due. Echoes non-empty on stdout if at least one item updated.
|
||||
shater_run_due() {
|
||||
@@ -81,11 +137,16 @@ shater_run_due() {
|
||||
if [ -n "$name" ] && [ "$en" = "1" ]; then
|
||||
ivl=$(uci -q get "shater.@subscription[$i].update_interval")
|
||||
secs=$(shater_ivl_secs "$ivl" "$DEFAULT_SUB_INTERVAL")
|
||||
stamp="$STAMP_DIR/sub.$name"
|
||||
stamp="$STAMP_DIR/sub.$(shater_safe_name "$name")"
|
||||
if shater_due "$stamp" "$secs"; then
|
||||
"$XRAYCTL" sub update "$name" >/dev/null 2>&1
|
||||
if "$XRAYCTL" sub update "$name" >/dev/null 2>&1; then
|
||||
shater_stamp "$stamp"
|
||||
changed=1
|
||||
else
|
||||
logger -t shater-cron -p daemon.warn \
|
||||
"sub update '$name' failed; retrying in ${RETRY_SECS}s"
|
||||
shater_stamp_retry "$stamp" "$secs"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
i=$(( i + 1 ))
|
||||
@@ -99,11 +160,16 @@ shater_run_due() {
|
||||
if [ -n "$name" ] && [ "$src" = "url" ]; then
|
||||
ivl=$(uci -q get "shater.@ruleset[$i].update_interval")
|
||||
secs=$(shater_ivl_secs "$ivl" "$DEFAULT_RS_INTERVAL")
|
||||
stamp="$STAMP_DIR/rs.$name"
|
||||
stamp="$STAMP_DIR/rs.$(shater_safe_name "$name")"
|
||||
if shater_due "$stamp" "$secs"; then
|
||||
"$XRAYCTL" ruleset update "$name" >/dev/null 2>&1
|
||||
if "$XRAYCTL" ruleset update "$name" >/dev/null 2>&1; then
|
||||
shater_stamp "$stamp"
|
||||
changed=1
|
||||
else
|
||||
logger -t shater-cron -p daemon.warn \
|
||||
"ruleset update '$name' failed; retrying in ${RETRY_SECS}s"
|
||||
shater_stamp_retry "$stamp" "$secs"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
i=$(( i + 1 ))
|
||||
@@ -112,20 +178,58 @@ shater_run_due() {
|
||||
[ -n "$changed" ] && echo 1
|
||||
}
|
||||
|
||||
# loop: the foreground body supervised by procd. Runs due items each tick and
|
||||
# exits when the stack is disabled so `reload`/`stop` cleanly tears it down.
|
||||
# Exposed as a custom rc.common action (see EXTRA_COMMANDS) for procd to re-exec.
|
||||
# Watchdog body for one tick: detect "interception live, engine dead". $1 is
|
||||
# the running dead-tick count; echoes the updated count.
|
||||
shater_watchdog() {
|
||||
local dead="$1" ks
|
||||
if [ ! -f "$RUN_JSON" ] || pidof xray >/dev/null 2>&1; then
|
||||
echo 0
|
||||
return
|
||||
fi
|
||||
dead=$(( dead + 1 ))
|
||||
if [ "$dead" -eq "$WATCHDOG_TICKS" ]; then
|
||||
ks=$(uci -q get shater.globals.kill_switch)
|
||||
if [ "$ks" = "closed" ]; then
|
||||
# Fail-closed is a POLICY: dead engine + standing rules == traffic
|
||||
# blocked, which is what the admin asked for. Keep it, but say so.
|
||||
logger -t shater-cron -p daemon.crit \
|
||||
"xray dead for $(( dead * TICK ))s with interception live; kill_switch=closed keeps LAN blocked — fix the engine or /etc/init.d/shater stop"
|
||||
else
|
||||
# Fail-open: durably stop the stack (clears the live-flag + tears
|
||||
# interception down) so the LAN returns to plain routing.
|
||||
logger -t shater-cron -p daemon.crit \
|
||||
"xray dead for $(( dead * TICK ))s with interception live; kill_switch=open — stopping shater (fail-open, LAN back to plain routing)"
|
||||
"$SHATER_INIT" stop
|
||||
dead=0
|
||||
fi
|
||||
fi
|
||||
echo "$dead"
|
||||
}
|
||||
|
||||
# loop: the foreground body supervised by procd. Never exits on its own — it
|
||||
# idles while disabled/inactive so procd is not respawn-churned by a
|
||||
# self-exiting body when the stack is off.
|
||||
loop() {
|
||||
local changed sched dead=0
|
||||
mkdir -p "$STAMP_DIR"
|
||||
while shater_enabled; do
|
||||
while :; do
|
||||
if shater_enabled && shater_active; then
|
||||
if shater_has_uplink; then
|
||||
changed=$(shater_run_due)
|
||||
# Schedule boundary: `schedule due` prints "1" only when the set of active
|
||||
# time-scheduled rules changed since the last tick, so we reconcile a few
|
||||
# times a day at window edges — not every minute.
|
||||
else
|
||||
changed=""
|
||||
fi
|
||||
# Schedule boundary: `schedule due` prints "1" only when the set of
|
||||
# active time-scheduled rules changed since the last tick, so we
|
||||
# reconcile a few times a day at window edges — not every minute.
|
||||
sched=$("$XRAYCTL" schedule due 2>/dev/null)
|
||||
if [ -n "$changed" ] || [ -n "$sched" ]; then
|
||||
"$XRAYCTL" reconcile >/dev/null 2>&1
|
||||
fi
|
||||
dead=$(shater_watchdog "$dead")
|
||||
else
|
||||
dead=0
|
||||
fi
|
||||
sleep "$TICK"
|
||||
done
|
||||
}
|
||||
@@ -138,7 +242,11 @@ start_service() {
|
||||
|
||||
procd_open_instance shater-cron
|
||||
# Re-exec ourselves as the loop body so procd supervises a single process.
|
||||
procd_set_param command /bin/sh "$INIT_SCRIPT" loop
|
||||
# Invoke through the rc.common shebang (NOT `/bin/sh $INIT_SCRIPT`) so the
|
||||
# `loop` action is dispatched by rc.common and procd tracks the resulting
|
||||
# foreground PID — running `/bin/sh <script> loop` detaches the loop from
|
||||
# procd (instance shows not-running, and procd respawn-churns it).
|
||||
procd_set_param command "$INIT_SCRIPT" loop
|
||||
procd_set_param respawn 3600 10 0 # threshold timeout always-retry
|
||||
procd_set_param file /etc/config/shater # restart the loop when UCI changes
|
||||
procd_set_param stdout 1
|
||||
@@ -148,7 +256,7 @@ start_service() {
|
||||
|
||||
reload_service() {
|
||||
# UCI changed: bounce the loop so new intervals/items take effect. If the
|
||||
# stack was disabled, the loop self-exits and start re-guards to no-op.
|
||||
# stack was disabled, start re-guards to a no-op.
|
||||
stop
|
||||
start
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# /etc/sysctl.d/99-shater.conf
|
||||
# Kernel knobs required by the TPROXY + policy-routing data plane.
|
||||
# Applied at boot by procd's sysctl service; apply now with:
|
||||
# sysctl -p /etc/sysctl.d/99-shater.conf
|
||||
# Applied at boot by procd's sysctl service; 30_shater-core also applies it
|
||||
# once at install time so a fresh install works without a reboot.
|
||||
|
||||
# Route between LAN and WAN.
|
||||
net.ipv4.ip_forward=1
|
||||
@@ -13,11 +13,16 @@ net.ipv4.conf.all.rp_filter=0
|
||||
net.ipv4.conf.default.rp_filter=0
|
||||
|
||||
# Allow routing to 127/8 so `ip route add local 0.0.0.0/0 dev lo table <N>`
|
||||
# delivers foreign-destination packets to the transparent socket.
|
||||
net.ipv4.conf.all.route_localnet=1
|
||||
# delivers foreign-destination packets to the transparent socket. Scoped to
|
||||
# `lo` only — that is the only path the tproxy local-delivery trick uses.
|
||||
# Setting it on `all` would make WAN-originated packets destined to 127/8
|
||||
# routable (a real anti-spoofing weakening we do not need).
|
||||
net.ipv4.conf.lo.route_localnet=1
|
||||
|
||||
# Accept packets with a local source address arriving on the loopback path.
|
||||
net.ipv4.conf.all.accept_local=1
|
||||
# Same scoping rationale: needed on `lo` for the looped tproxy packets, and
|
||||
# on `all` it would accept local-source spoofs from any interface incl. WAN.
|
||||
net.ipv4.conf.lo.accept_local=1
|
||||
|
||||
# Keep the source-address validity check happy for marked/looped packets.
|
||||
net.ipv4.conf.all.src_valid_mark=1
|
||||
|
||||
@@ -33,8 +33,15 @@ seed_rt_table 8192 shater
|
||||
# Seed the built-in preset packs (disabled) so the LuCI Rules page renders their
|
||||
# toggles. Idempotent: only creates a section that does not yet exist.
|
||||
seed_preset() {
|
||||
local sid="$1" name="$2"
|
||||
local sid="$1" name="$2" s n
|
||||
uci -q get "shater.$sid" >/dev/null 2>&1 && return 0
|
||||
# A pack section may already exist under a DIFFERENT section id (created by
|
||||
# the LuCI seeding or an older release) — match by pack name, not just id,
|
||||
# or we would duplicate the toggle.
|
||||
for s in $(uci -q show shater 2>/dev/null | sed -n "s/^shater\.\([^.=]*\)=preset$/\1/p"); do
|
||||
n=$(uci -q get "shater.$s.name")
|
||||
[ "$n" = "$name" ] && return 0
|
||||
done
|
||||
uci set "shater.$sid=preset"
|
||||
uci set "shater.$sid.name=$name"
|
||||
uci set "shater.$sid.enabled=0"
|
||||
@@ -49,4 +56,10 @@ fi
|
||||
# Bring the UCI schema forward on upgrade (idempotent; refuses a newer schema).
|
||||
[ -x /usr/bin/xrayctl ] && /usr/bin/xrayctl migrate >/dev/null 2>&1
|
||||
|
||||
# Apply our sysctl knobs NOW (boot applies them via procd's sysctl service, but
|
||||
# on a live opkg/apk install nothing else re-reads sysctl.d — without this, an
|
||||
# install→enable→apply flow hits the rp_filter "rules match but nothing works"
|
||||
# failure until the first reboot). Idempotent; unknown keys are ignored.
|
||||
[ -f /etc/sysctl.d/99-shater.conf ] && sysctl -p /etc/sysctl.d/99-shater.conf >/dev/null 2>&1
|
||||
|
||||
exit 0
|
||||
Reference in new issue
Block a user