Added core update through RAM for low budget routers, disabled ipv6_proxy (leak)

This commit is contained in:
Sam Latsin 2026-10-24 13:32:00 +03:00
parent 6723f4e2cb
commit 9743350fa5
2 changed files with 119 additions and 9 deletions

View File

@ -300,6 +300,11 @@ cron даёт, только если сервер не принял токен
| `GOMEMLIMIT` в `/etc/init.d/nikki` (только с `LITE=1`) | лимит памяти ядра для слабых роутеров, см. «Облегчённый режим» | | `GOMEMLIMIT` в `/etc/init.d/nikki` (только с `LITE=1`) | лимит памяти ядра для слабых роутеров, см. «Облегчённый режим» |
| переустановка `libcurl4 curl`, если curl сломан | `Error relocating ... symbol not found` | | переустановка `libcurl4 curl`, если curl сломан | `Error relocating ... symbol not found` |
Ещё `mihomo-kit.sh use` (и «Сохранить и применить») ставит `nikki.proxy.ipv6_proxy=0`, если на
роутере выключен IPv6 (`disable_ipv6=1` для `all` или `lo`, или IPv6 нет в ядре): иначе nikki
при старте пишет `Error: IPv6 is disabled on nexthop device` (`ip -6 route ... dev lo` для
tproxy). Включить обратно — `uci set nikki.proxy.ipv6_proxy=1`, когда IPv6 появится.
## Телефон (FlClash) ## Телефон (FlClash)
С роутера: LuCI → Настройка → галка «Конфиг для телефона» → «Сохранить и применить». На С роутера: LuCI → Настройка → галка «Конфиг для телефона» → «Сохранить и применить». На
@ -359,7 +364,17 @@ control-сервер и DERP идут по TCP через `dialer-proxy`. На
- `kit` (по умолчанию) — своя сборка `CORE_KIT`: официальное ядро с правками kit (см. «Ядро kit»). - `kit` (по умолчанию) — своя сборка `CORE_KIT`: официальное ядро с правками kit (см. «Ядро kit»).
Распакованному ядру нужно ~56 МБ во флеше: на роутерах с маленьким `/overlay` остаётся Распакованному ядру нужно ~56 МБ во флеше: на роутерах с маленьким `/overlay` остаётся
`stock`. Версии `CORE_OFFICIAL`/`CORE_KIT` задаются в `router/mihomo-kit.sh` — роутеры с `stock`.
Новое ядро ставится через оперативку, если в ней свободно ≥ 140 МБ (`MemAvailable`): пока
nikki работает, ядро скачивается и распаковывается в `/tmp/mihomo.new`, там же проверяется
`-v`. Потом nikki останавливается, текущее ядро копируется в `/tmp/mihomo.prev` и
удаляется из флеша, новое записывается на его место. Так во флеше нужно место только под одно
ядро. Если запись не удалась, возвращается старое. Если новое ядро после старта не ответило
по API (`/version`) за 40 с, kit откатывается на старое и запускает его. Копия в RAM после
этого удаляется: более старое ядро — через `MIHOMO_VERSION=…` в `kit.env` + `fix`. Если
оперативки мало, ядро распаковывается во флеш рядом со старым (как раньше, без отката).
Пропало питание, пока новое ядро писалось во флеш — `mihomo-kit.sh fix` скачает его заново. Версии `CORE_OFFICIAL`/`CORE_KIT` задаются в `router/mihomo-kit.sh` — роутеры с
выбором `official`/`kit` подтягивают их при обновлении kit. Явный `MIHOMO_VERSION=…` в выбором `official`/`kit` подтягивают их при обновлении kit. Явный `MIHOMO_VERSION=…` в
`kit.env` главнее выбора. Когда исправление появится в mihomo, вернуть официальный релиз. `kit.env` главнее выбора. Когда исправление появится в mihomo, вернуть официальный релиз.

View File

@ -634,6 +634,16 @@ csqtt_match_process() {
esac esac
} }
# IPv6 off on the router: nikki's IPv6 routes (ip -6 route ... dev lo for tproxy, dev
# <tun> for TUN) fail with "IPv6 is disabled on nexthop device", and there is no
# IPv6 to intercept anyway
ipv6_proxy_off() {
[ "$(uci -q get nikki.proxy.ipv6_proxy)" = 1 ] || return 0
[ ! -d /proc/sys/net/ipv6 ] || [ "$(cat /proc/sys/net/ipv6/conf/all/disable_ipv6 2>/dev/null)" = 1 ] ||
[ "$(cat /proc/sys/net/ipv6/conf/lo/disable_ipv6 2>/dev/null)" = 1 ] || return 0
uci set nikki.proxy.ipv6_proxy=0 && log "nikki: ipv6_proxy=0 (IPv6 is disabled on the router)"
}
# --- LITE (weak routers) ---------------------------------------------------- # --- LITE (weak routers) ----------------------------------------------------
# LITE=1: the profile gets the lite templates (tag lite), and here: GOMEMLIMIT for # LITE=1: the profile gets the lite templates (tag lite), and here: GOMEMLIMIT for
# mihomo, nikki's log level and process lookup, warnings about what eats memory. # mihomo, nikki's log level and process lookup, warnings about what eats memory.
@ -746,6 +756,7 @@ cmd_use() {
uci set nikki.config.profile="file:$1.yaml" uci set nikki.config.profile="file:$1.yaml"
lite_uci "$1" lite_uci "$1"
csqtt_match_process "$1" csqtt_match_process "$1"
ipv6_proxy_off
uci commit nikki uci commit nikki
mem_env "$1" mem_env "$1"
/etc/init.d/nikki restart /etc/init.d/nikki restart
@ -905,6 +916,12 @@ cmd_ts_login() {
# unpacked core size to expect, for the free space check (KiB) # unpacked core size to expect, for the free space check (KiB)
CORE_NEED_KB=60000 CORE_NEED_KB=60000
# a core update in RAM (/tmp): the new core and a copy of the current one, unpacked
CORE_RAM_NEED_KB=140000
CORE_RAM_NEW=/tmp/mihomo.new
CORE_RAM_PREV=/tmp/mihomo.prev
# seconds for a new core to answer the API before the rollback
CORE_START_WAIT=40
# is the installed core the wanted one? # is the installed core the wanted one?
core_ok() { core_ok() {
@ -961,23 +978,33 @@ core_fetch() {
return 1 return 1
} }
log "updating mihomo core ${cur:-none} -> $MIHOMO_VERSION" log "updating mihomo core ${cur:-none} -> $MIHOMO_VERSION"
# Streamed straight next to the binary: /tmp is RAM, and the unpacked core
# (~56 MB) plus the .gz do not fit on small routers. No .bak copy either (flash
# space); an older core comes back with MIHOMO_VERSION in /etc/nikki/kit.env + fix.
# A failed download keeps the current core: fix/update still start nikki.
bin=$(command -v mihomo || echo /usr/bin/mihomo) bin=$(command -v mihomo || echo /usr/bin/mihomo)
# leftovers of an interrupted update
rm -f "$bin.new" "$bin.bak" "$CORE_RAM_NEW" "$CORE_RAM_PREV" /tmp/mihomo.gz /tmp/mihomo
# Unpacked into RAM when it fits (the new core and, at install, a copy of the
# current one for the rollback): the flash then needs room for one core only.
# Otherwise streamed straight next to the binary (room for both on the flash).
new=$bin.new new=$bin.new
rm -f "$new" "$bin.bak" /tmp/mihomo.gz /tmp/mihomo _avail=$(awk '/^MemAvailable:/ {print $2}' /proc/meminfo 2>/dev/null)
if [ "${_avail:-0}" -ge "$CORE_RAM_NEED_KB" ]; then
new=$CORE_RAM_NEW
else
log "only ${_avail:-?} KB RAM free (need $CORE_RAM_NEED_KB): unpacking next to the binary, no rollback copy"
fi
# A failed download keeps the current core: fix/update still start nikki.
if ! curl -fsSL "$url" | gunzip > "$new" || ! chmod +x "$new" || if ! curl -fsSL "$url" | gunzip > "$new" || ! chmod +x "$new" ||
[ "$("$new" -v 2>/dev/null | awk '{print $3; exit}')" != "$MIHOMO_VERSION" ]; then [ "$("$new" -v 2>/dev/null | awk '{print $3; exit}')" != "$MIHOMO_VERSION" ]; then
rm -f "$new" rm -f "$new"
log "warning: core $MIHOMO_VERSION not installed (download, unpack or check failed: $url;" \ log "warning: core $MIHOMO_VERSION not installed (download, unpack or check failed: $url;" \
"free space in ${bin%/*}: $(df -h "${bin%/*}" 2>/dev/null | awk 'NR==2 {print $4}')), keeping ${cur:-the current one}" "free space in ${new%/*}: $(df -h "${new%/*}" 2>/dev/null | awk 'NR==2 {print $4}')), keeping ${cur:-the current one}"
return 1 return 1
fi fi
CORE_PENDING=new CORE_PENDING=new CORE_NEW=$new
} }
# the core at <path> reports the wanted version
core_is_wanted() { [ "$("$1" -v 2>/dev/null | awk '{print $3; exit}')" = "$MIHOMO_VERSION" ]; }
core_install() { core_install() {
case "${CORE_PENDING:-}" in case "${CORE_PENDING:-}" in
stock) stock)
@ -987,13 +1014,80 @@ core_install() {
log "core: the package's $("$STOCK_CORE" -v 2>/dev/null | awk '{print $3; exit}')" log "core: the package's $("$STOCK_CORE" -v 2>/dev/null | awk '{print $3; exit}')"
;; ;;
new) new)
if [ "$CORE_NEW" = "$bin.new" ]; then
mv "$bin.new" "$bin" mv "$bin.new" "$bin"
else
core_swap || { CORE_PENDING=""; return 1; }
fi
log "core: $(mihomo -v | head -n 1)" log "core: $(mihomo -v | head -n 1)"
;; ;;
esac esac
CORE_PENDING="" CORE_PENDING=""
} }
# nikki stopped, the new core in RAM: the current one goes to RAM too (a symlink
# to the package's core stays a symlink), its flash space is freed, then the new
# one is written. A failed write puts the old one back.
core_swap() {
CORE_PREV_LINK=""
rm -f "$CORE_RAM_PREV"
if [ -L "$bin" ]; then
CORE_PREV_LINK=$(readlink "$bin")
elif [ -f "$bin" ] && ! cp -p "$bin" "$CORE_RAM_PREV"; then
rm -f "$CORE_RAM_PREV" "$CORE_RAM_NEW"
log "warning: no room in RAM for a copy of the current core, keeping it"
return 1
fi
rm -f "$bin"
if cp "$CORE_RAM_NEW" "$bin.new" && chmod +x "$bin.new" && core_is_wanted "$bin.new" &&
mv "$bin.new" "$bin"; then
rm -f "$CORE_RAM_NEW"
return 0
fi
rm -f "$bin.new" "$CORE_RAM_NEW"
log "warning: writing core $MIHOMO_VERSION to ${bin%/*} failed" \
"(free: $(df -h "${bin%/*}" 2>/dev/null | awk 'NR==2 {print $4}')), putting the old one back"
core_restore
return 1
}
# the core saved by core_swap back in place
core_restore() {
rm -f "$bin"
if [ -n "$CORE_PREV_LINK" ]; then
ln -s "$CORE_PREV_LINK" "$bin"
elif [ -f "$CORE_RAM_PREV" ]; then
cp -p "$CORE_RAM_PREV" "$bin" || log "warning: could not put the old core back; run: mihomo-kit.sh fix"
fi
rm -f "$CORE_RAM_PREV"
CORE_PREV_LINK=""
}
# after nikki start with a just swapped core: the API answers with the wanted
# version within CORE_START_WAIT s, or the old core goes back. The RAM copy is
# dropped either way (an older core: MIHOMO_VERSION in kit.env + fix).
core_confirm() {
[ -f "$CORE_RAM_PREV" ] || [ -n "${CORE_PREV_LINK:-}" ] || return 0
_w=0
while [ "$_w" -lt "$CORE_START_WAIT" ]; do
case "$(api_get /version 2>/dev/null)" in
*"\"$MIHOMO_VERSION\""*)
rm -f "$CORE_RAM_PREV"
CORE_PREV_LINK=""
return 0
;;
esac
sleep 2
_w=$((_w + 2))
done
log "warning: core $MIHOMO_VERSION did not answer within ${CORE_START_WAIT}s, rolling back"
/etc/init.d/nikki stop 2>/dev/null
core_restore
/etc/init.d/nikki start
log "core: $(mihomo -v 2>/dev/null | head -n 1) (rolled back)"
return 1
}
# Tailscale control over port 80 gets broken by the ISP: force 443. # Tailscale control over port 80 gets broken by the ISP: force 443.
# OpenVPN: a provider with a fresh OTP right before mihomo starts, since the kit # OpenVPN: a provider with a fresh OTP right before mihomo starts, since the kit
# core connects as soon as it loads the provider (auto-connect). # core connects as soon as it loads the provider (auto-connect).
@ -1233,6 +1327,7 @@ cmd_fix() {
wan_metrics wan_metrics
dns_rebind_exempt dns_rebind_exempt
/etc/init.d/nikki start /etc/init.d/nikki start
core_confirm || true
} }
# --- setup wizard ----------------------------------------------------------- # --- setup wizard -----------------------------------------------------------