2755 lines
109 KiB
Bash
Executable File
2755 lines
109 KiB
Bash
Executable File
#!/bin/sh
|
||
# mihomo config kit for nikki on OpenWrt.
|
||
#
|
||
# Builds mihomo profiles from templates/ + per-profile env files, and keeps the
|
||
# router-side fixes in place (core version, Tailscale env, nikki bypass list).
|
||
#
|
||
# Layout on the router:
|
||
# /etc/nikki/kit/{templates,presets,router,luci} the kit (install.sh / update / tools/push.sh)
|
||
# /etc/nikki/profiles.d/common.env shared secrets/options
|
||
# /etc/nikki/profiles.d/<name>.env one file per profile (main, whitelist, ...)
|
||
# /etc/nikki/profiles/<name>.yaml generated, what nikki runs
|
||
#
|
||
# Usage:
|
||
# mihomo-kit.sh setup [--cli] first run: install, then settings in LuCI
|
||
# (--cli or no LuCI: questions here + build + start)
|
||
# mihomo-kit.sh configure <env> settings from an env file (LuCI form) -> write, build, start
|
||
# mihomo-kit.sh services <env> only SERVICES / SVC_* / POOLS / POOL_* (graph page) -> build, start
|
||
# mihomo-kit.sh build [name...] profiles.d/<name>.env -> profiles/<name>.yaml (default: all)
|
||
# mihomo-kit.sh use <name> switch nikki to profiles/<name>.yaml and restart
|
||
# mihomo-kit.sh update download the latest kit (KIT_URL) and rebuild
|
||
# mihomo-kit.sh check-update latest commit on the server vs the installed one
|
||
# mihomo-kit.sh update --apply update, then restart the current profile (and fix the core)
|
||
# mihomo-kit.sh auto-update [on|off] daily 04:00 update via cron; no argument = run it now
|
||
# mihomo-kit.sh fix re-apply core version + fixes (after a nikki upgrade)
|
||
# mihomo-kit.sh ts-login [-f] fresh Tailscale node, print its login URL
|
||
# mihomo-kit.sh csqtt on|off|state CSQTT tunnel (star-panel-csqtt) + group UPLINK, in order
|
||
# (-f: also when the node is already logged in)
|
||
# mihomo-kit.sh export > file all settings as one file; import <file> [--keep-local] on another router
|
||
# mihomo-kit.sh mobile new new secret link for the phone config (MOBILE=1)
|
||
# mihomo-kit.sh core <choice> mihomo core: stock (package) | official | kit (official + kit patches)
|
||
# mihomo-kit.sh pkg-install <ipk>... nikki / mihomo-meta / luci from .ipk files on a small
|
||
# flash: own space check, opkg --force-space, fix
|
||
# mihomo-kit.sh install packages, core, fixes, links (no questions)
|
||
# mihomo-kit.sh render <env>... print the YAML for env file(s) (last wins)
|
||
|
||
set -u
|
||
|
||
# resolve the /usr/bin symlink to find the kit
|
||
SELF=$(readlink -f "$0" 2>/dev/null || echo "$0")
|
||
KIT_DIR="${KIT_DIR:-$(cd "$(dirname "$SELF")/.." && pwd)}"
|
||
TPL_DIR="${TPL_DIR:-$KIT_DIR/templates}"
|
||
NIKKI_DIR="${NIKKI_DIR:-/etc/nikki}"
|
||
PROFILES_D="$NIKKI_DIR/profiles.d"
|
||
PROFILES_OUT="$NIKKI_DIR/profiles"
|
||
# mihomo core: the choice CORE in /etc/nikki/kit.env (LuCI select, "core <choice>")
|
||
# stock the core of the mihomo package (/usr/libexec/mihomo), nothing downloaded
|
||
# official MetaCubeX release CORE_OFFICIAL
|
||
# kit own build CORE_KIT (official + tools/core/*.patch: Tailscale through dialer-proxy,
|
||
# OpenVPN presenting as OpenVPN Connect)
|
||
# An explicit MIHOMO_VERSION in kit.env wins (e.g. MIHOMO_VERSION=v1.19.29).
|
||
CORE_OFFICIAL=v1.19.34
|
||
CORE_KIT=v1.19.34-ts8
|
||
# nikki packages (install): the OpenWrt-nikki release NIKKI_VERSION, mirrored into the
|
||
# kit repo's releases (tools/nikki-mirror.sh) - GitHub is often unreachable from the router
|
||
NIKKI_VERSION=v1.26.2
|
||
STOCK_CORE=/usr/libexec/mihomo
|
||
KIT_ENV=${KIT_ENV:-/etc/nikki/kit.env}
|
||
[ -f "$KIT_ENV" ] && . "$KIT_ENV"
|
||
: "${CORE:=kit}"
|
||
if [ -z "${MIHOMO_VERSION:-}" ]; then
|
||
case "$CORE" in
|
||
stock) MIHOMO_VERSION=stock ;;
|
||
official) MIHOMO_VERSION=$CORE_OFFICIAL ;;
|
||
*) MIHOMO_VERSION=$CORE_KIT ;;
|
||
esac
|
||
fi
|
||
# where mihomo-linux-<arch>-<version>.gz is downloaded from. -tsN: own build with
|
||
# tools/core/*.patch (see README, "Ядро kit") in the kit repo's releases; other
|
||
# versions: upstream MetaCubeX/mihomo releases.
|
||
case "$MIHOMO_VERSION" in
|
||
*-ts*) : "${MIHOMO_BASE:=https://git.sam-hub.net/sam/mihomo-kit/releases/download/core-$MIHOMO_VERSION}" ;;
|
||
*) : "${MIHOMO_BASE:=https://github.com/MetaCubeX/mihomo/releases/download/$MIHOMO_VERSION}" ;;
|
||
esac
|
||
: "${KIT_URL:=https://git.sam-hub.net/sam/mihomo-kit/archive/main.tar.gz}"
|
||
# where nikki_<arch>-<branch>.tar.gz is downloaded from, tried in this order
|
||
: "${NIKKI_BASES:=https://git.sam-hub.net/sam/mihomo-kit/releases/download/nikki-$NIKKI_VERSION https://github.com/nikkinikki-org/OpenWrt-nikki/releases/download/$NIKKI_VERSION}"
|
||
|
||
log() { echo "$*" >&2; }
|
||
die() { log "error: $*"; exit 1; }
|
||
|
||
# --- rendering --------------------------------------------------------------
|
||
# Template syntax:
|
||
# file NN-<module>[.<tag>...][.each].yaml included if module and tags are active;
|
||
# .each = once per item of the module:
|
||
# sub - subscription, boot - seed node
|
||
# line ... #@tag[,!tag] kept only if the conditions hold
|
||
# line ... ${@VAR} ... repeated for every word of VAR
|
||
# line ... ${@@VAR} ... repeated for every line of VAR
|
||
# text ${VAR} replaced with the variable
|
||
|
||
# ovpn_remote <file.ovpn> names|ips: the hosts of its "remote host [port] [proto]"
|
||
# lines, names or IPv4 addresses
|
||
ovpn_remote() {
|
||
awk -v ip="$([ "$2" = ips ] && echo 1)" '$1 == "remote" && ($2 ~ /^[0-9.]+$/) == (ip == 1) { print $2 }' "$1" 2>/dev/null |
|
||
sort -u | tr '\n' ' ' | sed 's/ $//'
|
||
}
|
||
|
||
# ovpn_routes_of <file.ovpn>: its "route <net> <mask>" lines as CIDR
|
||
ovpn_routes_of() {
|
||
awk '$1 == "route" && $2 ~ /^[0-9.]+$/ {
|
||
m = $3 ~ /^[0-9.]+$/ ? $3 : "255.255.255.255"
|
||
split(m, o, ".")
|
||
b = 0
|
||
for (i = 1; i <= 4; i++) for (x = o[i]; x > 0; x = int(x / 2)) b += x % 2
|
||
print $2 "/" b
|
||
}' "$1" 2>/dev/null | tr '\n' ' ' | sed 's/ $//'
|
||
}
|
||
|
||
set_defaults() {
|
||
: "${TARGET:=router}" "${LOCATION:=main}"
|
||
# old names of the profiles
|
||
case "$LOCATION" in home) LOCATION=main ;; street) LOCATION=whitelist ;; esac
|
||
: "${BOOT:=1}" "${TORRENT:=1}" "${PUSH:=1}" "${OPENVPN:=0}" "${TAILSCALE:=0}" "${TS_EXIT:=0}"
|
||
: "${SUBS:=}" "${RU_IPS:=}" "${HY2:=}"
|
||
: "${FOREIGN_IPS:=}" "${MY_IPS:=}" "${RU_DOMAINS:=}" "${FOREIGN_DOMAINS:=}" "${MY_DOMAINS:=}"
|
||
: "${LOCAL_HOSTS:=}" "${MY_LINKS:=}" "${MY_SERVERS_FILE:=$NIKKI_DIR/my-servers}"
|
||
: "${RULESET_URL:=https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release}"
|
||
: "${SERVICES:=}" "${POOLS:=}" "${GEOSITE_URL:=https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@meta/geo/geosite}"
|
||
: "${BOOT_LINKS:=}"
|
||
: "${BOOT_SERVER:=}" "${BOOT_PORT:=443}" "${BOOT_UUID:=}" "${BOOT_SNI:=}" "${BOOT_PBK:=}" "${BOOT_SID:=}"
|
||
: "${TS_HOSTNAME:=mihomo}" "${TS_DOMAINS:=}"
|
||
: "${HWID_UA:=v2rayN/9.99}" "${HWID_OS:=}" "${HWID_OS_VER:=}" "${HWID_MODEL:=}" "${HWID_ID:=}"
|
||
: "${OVPN_PROVIDER:=openvpn}" "${OVPN_GROUP:=OPENVPN}" "${OVPN_FILE:=$NIKKI_DIR/openvpn.ovpn}"
|
||
# the VPN server (the remote lines of the .ovpn) and the networks that go through it
|
||
: "${OVPN_SERVER_HOST:=$(ovpn_remote "$OVPN_FILE" names)}" "${OVPN_SERVER_IPS:=$(ovpn_remote "$OVPN_FILE" ips)}"
|
||
: "${OVPN_ROUTES:=}"
|
||
: "${OVPN_CHECK_URL:=https://www.gstatic.com/generate_204}" "${TS_CHECK_URL:=http://100.69.216.50:8080}"
|
||
: "${CSQTT:=0}" "${CSQTT_IFACE:=csqtt0}" "${CSQTT_PROCESS:=csqtt}"
|
||
: "${LITE:=0}"
|
||
}
|
||
|
||
compute_tags() {
|
||
TAGS=" base sub $TARGET "
|
||
[ "$BOOT" = 1 ] && TAGS="$TAGS boot "
|
||
if [ "$TARGET" = router ]; then
|
||
TAGS="$TAGS $LOCATION "
|
||
[ "$TORRENT" = 1 ] && TAGS="$TAGS torrent "
|
||
[ "$PUSH" = 1 ] && TAGS="$TAGS push "
|
||
[ "$OPENVPN" = 1 ] && TAGS="$TAGS openvpn "
|
||
if [ "$TAILSCALE" = 1 ]; then
|
||
TAGS="$TAGS tailscale "
|
||
[ "$TS_EXIT" = 1 ] && TAGS="$TAGS ts_exit "
|
||
fi
|
||
[ "$CSQTT" = 1 ] && TAGS="$TAGS csqtt "
|
||
# weak routers: rarer health checks, lighter sniffer, quieter core
|
||
[ "$LITE" = 1 ] && TAGS="$TAGS lite "
|
||
# own servers in the LAN (LOCAL_HOSTS): only the router is always at home
|
||
[ -n "$LOCAL_HOSTS" ] && TAGS="$TAGS local_hosts "
|
||
# own servers as links (MY_LINKS): a file on the router, the phone cannot read it
|
||
[ -n "$MY_LINKS" ] && TAGS="$TAGS my_links "
|
||
fi
|
||
# pools (pools_vars): a group each; services (services_vars): a group and rules each,
|
||
# geosite rule-providers
|
||
[ -n "$POOLS" ] && TAGS="$TAGS pool "
|
||
[ -n "$SERVICES" ] && TAGS="$TAGS svc "
|
||
# UPLINK (what the nodes connect through): with CSQTT or a pool offered there
|
||
case "$TAGS" in *" csqtt "*) TAGS="$TAGS uplink " ;; esac
|
||
for _p in $POOLS; do
|
||
eval "_u=\${$(pool_key "$_p")_UPLINK:-0}"
|
||
case "$TAGS" in *" uplink "*) ;; *) [ "$_u" = 1 ] && TAGS="$TAGS uplink " ;; esac
|
||
done
|
||
# CSQTT tunnel (star-panel-csqtt): last in MAIN (plain exit through its server)
|
||
CSQTT_MAIN=""
|
||
case "$TAGS" in *" csqtt "*) CSQTT_MAIN=", CSQTT" ;; esac
|
||
# MY_SUB_LIST "a-my, b-my": providers of the "[MY] ..." nodes (group MY)
|
||
SUB_LIST="" MY_SUB_LIST="" _i=0
|
||
for _p in $SUB_PAIRS; do
|
||
if ! sub_off "$_i" "${_p%%=*}"; then
|
||
SUB_LIST="${SUB_LIST:+$SUB_LIST, }${_p%%=*}"
|
||
MY_SUB_LIST="${MY_SUB_LIST:+$MY_SUB_LIST, }${_p%%=*}-my"
|
||
fi
|
||
_i=$((_i + 1))
|
||
done
|
||
# own servers of the settings (own_servers_vars): proxies in the profile and in group MY
|
||
[ -n "$OWN_BODIES" ] && TAGS="$TAGS own_srv "
|
||
# MY has servers for sure: own ones or links (not only maybe [MY] nodes)
|
||
case "$TAGS" in *" own_srv "* | *" my_links "*)
|
||
TAGS="$TAGS own "
|
||
;;
|
||
esac
|
||
case "$TAGS" in *" my_links "*) MY_SUB_LIST="${MY_SUB_LIST:+$MY_SUB_LIST, }my-links" ;; esac
|
||
# OpenVPN through OVPN-EXIT (a RU node): whitelist and abroad
|
||
case "$TAGS" in *" router "*" whitelist "* | *" router "*" foreign "*) TAGS="$TAGS ovpn_exit " ;; esac
|
||
# own servers through MY-EXIT: whitelist and the phone (often on whitelists)
|
||
case "$TAGS" in *" whitelist "* | *" mobile "*) TAGS="$TAGS my_exit " ;; esac
|
||
# MY_SUB_BASE: the same without the providers of nodes with an entry (my_node_vars)
|
||
MY_SUB_BASE=$MY_SUB_LIST
|
||
export SUB_LIST MY_SUB_LIST CSQTT_MAIN
|
||
}
|
||
|
||
# vless_parse <vless://uuid@host:port?...&sni=..&pbk=..&sid=..#name>
|
||
# -> _vs_server _vs_port _vs_uuid _vs_sni _vs_pbk _vs_sid (empty when missing)
|
||
vless_parse() {
|
||
_l=${1#vless://}
|
||
_l=${_l%%#*}
|
||
_vs_uuid=${_l%%@*}
|
||
_hp=${_l#*@}
|
||
_hp=${_hp%%\?*}
|
||
_vs_server=${_hp%:*}
|
||
_vs_port=${_hp##*:}
|
||
case "$_vs_port" in '' | *[!0-9]*) _vs_port=443 ;; esac
|
||
_q="&${_l#*\?}&"
|
||
_vs_sni=$(vless_qv sni) _vs_pbk=$(vless_qv pbk) _vs_sid=$(vless_qv sid)
|
||
}
|
||
vless_qv() { _v=${_q#*&$1=}; [ "$_v" = "$_q" ] || echo "${_v%%&*}"; }
|
||
|
||
# BOOT seeds: BOOT_LINKS (vless links, space/newline separated) or the old single
|
||
# BOOT_SERVER/PORT/UUID/SNI/PBK/SID -> SEED_ITEMS "name|server|port|uuid|sni|pbk|sid ...",
|
||
# SEED_LIST "seed, seed2".
|
||
boot_seeds() {
|
||
SEED_ITEMS="" SEED_LIST="" _k=1
|
||
if [ -n "$BOOT_LINKS" ]; then
|
||
set -f
|
||
for _l in $BOOT_LINKS; do
|
||
vless_parse "$_l"
|
||
_n=seed
|
||
[ "$_k" -gt 1 ] && _n=seed$_k
|
||
SEED_ITEMS="${SEED_ITEMS:+$SEED_ITEMS }$_n|$_vs_server|$_vs_port|$_vs_uuid|$_vs_sni|$_vs_pbk|$_vs_sid"
|
||
_k=$((_k + 1))
|
||
done
|
||
set +f
|
||
elif [ -n "$BOOT_SERVER" ]; then
|
||
SEED_ITEMS="seed|$BOOT_SERVER|$BOOT_PORT|$BOOT_UUID|$BOOT_SNI|$BOOT_PBK|$BOOT_SID"
|
||
fi
|
||
for _it in $SEED_ITEMS; do
|
||
SEED_LIST="${SEED_LIST:+$SEED_LIST, }${_it%%|*}"
|
||
done
|
||
export SEED_LIST
|
||
}
|
||
|
||
# seed_vars <item>: variables for templates/proxies/*-boot.each.yaml
|
||
seed_vars() {
|
||
_old_ifs=$IFS
|
||
IFS='|'
|
||
# shellcheck disable=SC2086
|
||
set -- $1
|
||
IFS=$_old_ifs
|
||
SEED_NAME=$1 SEED_SERVER=${2:-} SEED_PORT=${3:-} SEED_UUID=${4:-} SEED_SNI=${5:-} SEED_PBK=${6:-} SEED_SID=${7:-}
|
||
export SEED_NAME SEED_SERVER SEED_PORT SEED_UUID SEED_SNI SEED_PBK SEED_SID
|
||
}
|
||
|
||
# Subscription ids (provider names, keys SUB_<ID>_*). A SUBS word is "url" or
|
||
# "name=url"; without a name the id comes from the domain:
|
||
# https://sub.kittyvpn.com/x -> kittyvpn, https://a.b.co.uk/ -> b
|
||
# Repeats get 2, 3, ...
|
||
sub_auto_id() {
|
||
_h=${1#*://}
|
||
_h=${_h%%[/?#]*}
|
||
_h=${_h##*@}
|
||
_h=$(printf '%s' "${_h%:*}" | tr 'A-Z' 'a-z')
|
||
case "$_h" in *.*) _h=${_h%.*} ;; esac
|
||
while :; do
|
||
case "$_h" in
|
||
*.co | *.com | *.net | *.org | *.gov | *.edu | *.ac) _h=${_h%.*} ;;
|
||
*) break ;;
|
||
esac
|
||
done
|
||
_h=$(printf '%s' "${_h##*.}" | sed 's/[^a-z0-9_]/_/g')
|
||
case "$_h" in
|
||
'') echo sub ;;
|
||
[0-9]*) echo "sub$_h" ;;
|
||
*) echo "$_h" ;;
|
||
esac
|
||
}
|
||
|
||
# SUBS -> SUB_PAIRS="id=url id=url ..."
|
||
sub_pairs() {
|
||
SUB_PAIRS="" _seen=" "
|
||
set -f
|
||
for _w in $SUBS; do
|
||
_n=${_w%%=*} _u=${_w#*=}
|
||
case "$_n" in "$_w" | '' | *[!A-Za-z0-9_-]*) _n=$(sub_auto_id "$_w") _u=$_w ;; esac
|
||
_n=$(printf '%s' "$_n" | tr 'A-Z-' 'a-z_')
|
||
_id=$_n _k=2
|
||
while case "$_seen" in *" $_id "*) true ;; *) false ;; esac; do
|
||
_id=$_n$_k _k=$((_k + 1))
|
||
done
|
||
_seen="$_seen$_id "
|
||
SUB_PAIRS="${SUB_PAIRS:+$SUB_PAIRS }$_id=$_u"
|
||
done
|
||
set +f
|
||
}
|
||
|
||
# sub_get <index> <id> <KEY>: SUB_<ID>_<KEY>, else the old SUB<index>_<KEY>
|
||
sub_get() {
|
||
_K=$(printf '%s' "$2" | tr 'a-z' 'A-Z')
|
||
eval "printf '%s' \"\${SUB_${_K}_$3:-\${SUB$1_$3:-}}\""
|
||
}
|
||
|
||
# sub_off <index> <id>: SUB_<ID>_DISABLED=1 keeps the subscription (id, settings)
|
||
# but leaves it out of the profile
|
||
sub_off() { [ "$(sub_get "$1" "$2" DISABLED)" = 1 ]; }
|
||
|
||
check_vars() {
|
||
[ -n "$SUBS" ] || die "SUBS is empty (subscription URLs)"
|
||
case "$TARGET" in router | mobile) ;; *) die "TARGET must be router or mobile" ;; esac
|
||
case "$LOCATION" in main | whitelist | foreign) ;; *) die "LOCATION must be main, whitelist or foreign" ;; esac
|
||
set -f
|
||
for _l in $MY_LINKS; do
|
||
case "$_l" in
|
||
vless://?* | vmess://?* | trojan://?* | ss://?* | hysteria2://?* | hy2://?* | tuic://?* | anytls://?*) ;;
|
||
*) die "MY_LINKS: '${_l%%\?*}' is not a vless/vmess/trojan/ss/hysteria2/tuic/anytls link" ;;
|
||
esac
|
||
done
|
||
set +f
|
||
if [ "$BOOT" = 1 ]; then
|
||
[ -n "$SEED_ITEMS" ] || die "BOOT=1 but no BOOT_LINKS (vless links of the seed nodes)"
|
||
for _it in $SEED_ITEMS; do
|
||
seed_vars "$_it"
|
||
for v in SERVER UUID SNI PBK SID; do
|
||
eval "[ -n \"\$SEED_$v\" ]" || die "BOOT $SEED_NAME: $v is empty (vless link needs host, uuid, sni, pbk, sid)"
|
||
done
|
||
done
|
||
fi
|
||
i=0 _on=0
|
||
for _pr in $SUB_PAIRS; do
|
||
_id=${_pr%%=*}
|
||
if sub_off "$i" "$_id"; then
|
||
i=$((i + 1))
|
||
continue
|
||
fi
|
||
_on=1
|
||
case "$(sub_get "$i" "$_id" PROXY)" in
|
||
BOOT) [ "$BOOT" = 1 ] || die "subscription $_id: PROXY=BOOT but BOOT=0" ;;
|
||
esac
|
||
if [ "$(sub_get "$i" "$_id" HWID)" = 1 ]; then
|
||
for v in HWID_OS HWID_OS_VER HWID_MODEL HWID_ID; do
|
||
eval "[ -n \"\${$v}\" ]" || die "$v is empty (subscription $_id has HWID=1)"
|
||
done
|
||
fi
|
||
i=$((i + 1))
|
||
done
|
||
[ "$_on" = 1 ] || die "all subscriptions are disabled (SUB_<ID>_DISABLED=1)"
|
||
for _n in $HY2; do
|
||
case "$_n" in *[!A-Za-z0-9_-]*) die "HY2: bad server name $_n (letters, digits, _ -)" ;; esac
|
||
_k=$(hy2_key "$_n")
|
||
for v in SERVER PORT PASSWORD; do
|
||
eval "[ -n \"\${${_k}_$v:-}\" ]" || die "${_k}_$v is empty (hysteria2 server $_n)"
|
||
done
|
||
done
|
||
}
|
||
|
||
# hy2_key <name>: HY2_<NAME> prefix of the server's keys (upper case, - -> _)
|
||
hy2_key() { printf 'HY2_%s' "$(printf '%s' "$1" | tr 'a-z-' 'A-Z_')"; }
|
||
|
||
# YAML double-quoted string body
|
||
yq() { printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'; }
|
||
|
||
# per-subscription variables for the .each templates: sub_vars <index> <id> <url>
|
||
# (ID = id in upper case; the old SUB<index>_* keys still work)
|
||
# SUB_<ID>_PROXY BOOT-AUTO (default) | BOOT | DIRECT | FOREIGN | any proxy/group | none
|
||
# SUB_<ID>_UA User-Agent (default mihomo, with HWID: HWID_UA)
|
||
# SUB_<ID>_HWID=1 send x-device-os / x-ver-os / x-device-model / x-hwid from HWID_*
|
||
# SUB_<ID>_HEADERS extra headers: "key=value; key2=value 2"
|
||
sub_vars() {
|
||
SUB_NAME="$2" SUB_URL="$3"
|
||
_p=$(sub_get "$1" "$2" PROXY) _ua=$(sub_get "$1" "$2" UA) _hw=$(sub_get "$1" "$2" HWID)
|
||
_h=$(sub_get "$1" "$2" HEADERS)
|
||
[ -n "$_p" ] || _p=BOOT-AUTO
|
||
[ "$_p" = none ] && _p=""
|
||
# a subscription on an own server in the LAN: no proxy reaches it
|
||
is_local_url "$3" && _p=DIRECT
|
||
if [ "$_hw" = 1 ]; then
|
||
[ -n "$_ua" ] || _ua=$HWID_UA
|
||
_h="x-device-os=$HWID_OS;x-ver-os=$HWID_OS_VER;x-device-model=$HWID_MODEL;x-hwid=$HWID_ID${_h:+;$_h}"
|
||
fi
|
||
SUB_PROXY=$_p
|
||
SUB_MY_EXCLUDE=""
|
||
[ -n "${MY_NODE_ENTRIES:-}" ] && SUB_MY_EXCLUDE=$(yq "$(my_node_re "$2")")
|
||
SUB_UA=$(yq "${_ua:-mihomo}")
|
||
SUB_HEADERS=""
|
||
_old_ifs=$IFS
|
||
IFS=';'
|
||
set -f
|
||
for _item in $_h; do
|
||
_item=$(printf '%s' "$_item" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
|
||
[ -n "$_item" ] || continue
|
||
_k=$(printf '%s' "${_item%%=*}" | sed 's/[[:space:]]*$//')
|
||
_v=$(printf '%s' "${_item#*=}" | sed 's/^[[:space:]]*//')
|
||
SUB_HEADERS="${SUB_HEADERS:+$SUB_HEADERS
|
||
}$_k: [\"$(yq "$_v")\"]"
|
||
done
|
||
set +f
|
||
IFS=$_old_ifs
|
||
export SUB_NAME SUB_URL SUB_PROXY SUB_UA SUB_HEADERS SUB_MY_EXCLUDE
|
||
}
|
||
|
||
# hy2_json <name>: an old own hysteria2 server of the settings (HY2_<NAME>_SERVER, _PORT,
|
||
# _PASSWORD; _OBFS_PASSWORD = salamander; _SNI, _INSECURE=1, _UP, _DOWN) as a stored
|
||
# line of own servers (see own_servers_vars)
|
||
hy2_json() {
|
||
_k=$(hy2_key "$1")
|
||
eval "_sv=\${${_k}_SERVER} _po=\${${_k}_PORT} _pw=\${${_k}_PASSWORD} _ob=\${${_k}_OBFS_PASSWORD:-}
|
||
_sn=\${${_k}_SNI:-} _in=\${${_k}_INSECURE:-0} _up=\${${_k}_UP:-} _dn=\${${_k}_DOWN:-}"
|
||
case "$_po" in '' | *[!0-9]*) _po="\"$(yq "$_po")\"" ;; esac
|
||
printf '{"name":"%s","type":"hysteria2","server":"%s","port":%s,"password":"%s"' \
|
||
"$(yq "$1")" "$(yq "$_sv")" "$_po" "$(yq "$_pw")"
|
||
[ -n "$_ob" ] && printf ',"obfs":"salamander","obfs-password":"%s"' "$(yq "$_ob")"
|
||
[ -n "$_sn" ] && printf ',"sni":"%s"' "$(yq "$_sn")"
|
||
[ "$_in" = 1 ] && printf ',"skip-cert-verify":true'
|
||
[ -n "$_up" ] && printf ',"up":"%s"' "$(yq "$_up")"
|
||
[ -n "$_dn" ] && printf ',"down":"%s"' "$(yq "$_dn")"
|
||
printf ',"udp":true}\n'
|
||
}
|
||
|
||
# Own servers (LuCI "Свои серверы"): MY_SERVERS_FILE holds one JSON proxy per line
|
||
# with "name" first (luci/servers.js), plus the old HY2_* keys -> OWN_PLAIN, the lines
|
||
# without an entry of their own and without the leading "{" (templates/proxies puts the
|
||
# kit's dialer-proxy in front), OWN_ENTRY, the lines with one (LuCI "Вход": their own
|
||
# "dialer-proxy", kept in every profile), OWN_BODIES, all lines as OWN_PLAIN (for the
|
||
# chains' copies, which dial through their entry), and OWN_LIST '"a", "b"' for group MY. "$" becomes \u0024: the template engine would read
|
||
# ${...} in a password, JSON and YAML both read the escape.
|
||
own_servers_vars() {
|
||
OWN_BODIES="" OWN_PLAIN="" OWN_ENTRY="" OWN_LIST="" OWN_NAMES=""
|
||
_lines=$(
|
||
[ -f "$MY_SERVERS_FILE" ] && grep -v '^[[:space:]]*$' "$MY_SERVERS_FILE"
|
||
for _n in $HY2; do hy2_json "$_n"; done
|
||
)
|
||
[ -n "$_lines" ] || return 0
|
||
_names=$(printf '%s\n' "$_lines" | sed -nE 's/^\{"name":("([^"\\]|\\.)*"),.*/\1/p')
|
||
[ "$(printf '%s\n' "$_names" | grep -c .)" = "$(printf '%s\n' "$_lines" | grep -c .)" ] ||
|
||
die "$MY_SERVERS_FILE: a line is not {\"name\":...} (save the servers in LuCI again)"
|
||
_dup=$(printf '%s\n' "$_names" | sort | uniq -d | head -n 1)
|
||
[ -z "$_dup" ] || die "own servers: the name $_dup repeats"
|
||
OWN_NAMES=$_names
|
||
OWN_BODIES=$(printf '%s\n' "$_lines" | sed 's/^{//; s/,"dialer-proxy":"[^"]*"//; s/\$/\\u0024/g')
|
||
OWN_PLAIN=$(printf '%s\n' "$_lines" | grep -v '"dialer-proxy":' | sed 's/^{//; s/\$/\\u0024/g')
|
||
OWN_ENTRY=$(printf '%s\n' "$_lines" | grep '"dialer-proxy":' | sed 's/^/- /; s/\$/\\u0024/g')
|
||
OWN_LIST=$(printf '%s\n' "$_names" | sed 's/\$/\\u0024/g' | awk '{ printf "%s%s", (NR > 1 ? ", " : ""), $0 }')
|
||
}
|
||
|
||
# [MY] nodes of the subscriptions with an entry of their own (LuCI «Свои серверы» →
|
||
# «Вход»): MY_NODE_ENTRIES, one "<ENTRY>|<id>-my|<exact node name>" per line, stored in
|
||
# common.env as MY_NODE_1, MY_NODE_2, ... (one line each: my_nodes_join). Such a node
|
||
# leaves the provider <id>-my (its exclude-filter, SUB_MY_EXCLUDE) for <id>-my-via-<ENTRY>
|
||
# (providers/16-myvia: the same file, only these nodes, dialer-proxy <ENTRY> in every
|
||
# profile), which goes wherever <id>-my goes (my_via_expand). MYVIA_ITEMS "<id>|<ENTRY>".
|
||
my_node_vars() {
|
||
MYVIA_ITEMS=""
|
||
: "${MY_NODE_ENTRIES:=$(my_nodes_join)}"
|
||
[ -n "$MY_NODE_ENTRIES" ] || return 0
|
||
MYVIA_ITEMS=$(printf '%s\n' "$MY_NODE_ENTRIES" | while IFS='|' read -r _me _mp _mn; do
|
||
[ -n "$_me" ] && [ -n "$_mn" ] || continue
|
||
case "$_mp" in *-my) ;; *) die "MY_NODE_ENTRIES: $_mp is not a provider of [MY] nodes (<id>-my)" ;; esac
|
||
# a subscription that is off: its nodes are not in the profile
|
||
case ", $MY_SUB_BASE, " in *", $_mp, "*) echo "${_mp%-my}|$_me" ;; esac
|
||
done | awk '!seen[$0]++') || exit 1
|
||
[ -n "$MYVIA_ITEMS" ] || return 0
|
||
TAGS="$TAGS myvia "
|
||
MY_SUB_LIST=$(my_via_expand "$MY_SUB_BASE")
|
||
export MY_SUB_LIST
|
||
}
|
||
|
||
# my_nodes_join: MY_NODE_1, MY_NODE_2, ... of the settings, one per line
|
||
my_nodes_join() {
|
||
_mk=1
|
||
while eval "[ -n \"\${MY_NODE_$_mk+x}\" ]"; do
|
||
eval "printf '%s\\n' \"\$MY_NODE_$_mk\""
|
||
_mk=$((_mk + 1))
|
||
done
|
||
}
|
||
|
||
# my_via_expand "a-my, b, ...": the list with <id>-my-via-<ENTRY> after each <id>-my
|
||
my_via_expand() {
|
||
[ -n "$MYVIA_ITEMS" ] || { printf '%s' "$1"; return; }
|
||
printf '%s\n' "$1" | tr ',' '\n' | sed 's/^ *//' | while read -r _vp; do
|
||
[ -n "$_vp" ] || continue
|
||
echo "$_vp"
|
||
case "$_vp" in *-my) printf '%s\n' "$MYVIA_ITEMS" | awk -F'|' -v id="${_vp%-my}" '$1 == id { print $1 "-my-via-" $2 }' ;; esac
|
||
done | awk '{ printf "%s%s", (NR > 1 ? ", " : ""), $0 }'
|
||
}
|
||
|
||
# my_node_re <id> [ENTRY]: the exact names of its [MY] nodes with an entry (that one) as
|
||
# one anchored regex, literal (backtick separates filters in mihomo: encoded); nothing if none
|
||
my_node_re() {
|
||
printf '%s\n' "${MY_NODE_ENTRIES:-}" | awk -F'|' -v p="$1-my" -v e="${2:-}" '
|
||
$2 == p && (e == "" || $1 == e) { n = $0; sub(/^[^|]*\|[^|]*\|/, "", n); if (n != "") print n }' |
|
||
sed 's/[][\\.^$*+?(){}|]/\\&/g; s/`/\\x60/g' | awk '{ printf "%s%s", (NR > 1 ? "|" : "^("), $0 } END { if (NR) print ")$" }'
|
||
}
|
||
|
||
# myvia_vars "<id>|<ENTRY>": MV_NAME MV_ENTRY MV_FILTER (+ the subscription's SUB_* for the phone)
|
||
myvia_vars() {
|
||
_mid=${1%%|*} MV_ENTRY=${1#*|}
|
||
MV_NAME="$_mid-my-via-$MV_ENTRY"
|
||
MV_FILTER=$(yq "$(my_node_re "$_mid" "$MV_ENTRY")")
|
||
_i=0
|
||
for _pr in $SUB_PAIRS; do
|
||
[ "${_pr%%=*}" = "$_mid" ] && sub_vars "$_i" "$_mid" "${_pr#*=}"
|
||
_i=$((_i + 1))
|
||
done
|
||
export MV_NAME MV_ENTRY MV_FILTER
|
||
}
|
||
|
||
# own_entries_check (after pools_vars): an own server's entry is FOREIGN, RU, DIRECT
|
||
# or a pool that does not hold the server itself (that would be a loop)
|
||
own_entries_check() {
|
||
printf '%s\n' "$OWN_ENTRY" | sed -nE 's/^- \{"name":("([^"\\]|\\.)*"),.*"dialer-proxy":"([^"]*)".*/\3 \1/p' |
|
||
while read -r _oe _on; do
|
||
case " FOREIGN RU DIRECT$POOL_GROUPS" in *" $_oe "*) ;; *) die "own server $_on: entry $_oe is not FOREIGN, RU, DIRECT or a pool" ;; esac
|
||
case "$_oe" in FOREIGN | RU | DIRECT) continue ;; esac
|
||
# pool_vars sets _n, _e and others of its own
|
||
pool_vars "$(printf '%s' "$_oe" | tr 'A-Z' 'a-z')"
|
||
printf '%s\n' "$POOL_JSON" | grep -qxF "$_on" && die "own server $_on: its entry is the pool $_oe that holds it (a loop)"
|
||
true
|
||
done || exit 1
|
||
# [MY] nodes: the same entries; a pool with their subscription's [MY] nodes would be a loop
|
||
printf '%s\n' "$MYVIA_ITEMS" | while IFS='|' read -r _mi _oe; do
|
||
[ -n "$_mi" ] || continue
|
||
case " FOREIGN RU DIRECT$POOL_GROUPS" in *" $_oe "*) ;; *) die "[MY] nodes of $_mi: entry $_oe is not FOREIGN, RU, DIRECT or a pool" ;; esac
|
||
case "$_oe" in FOREIGN | RU | DIRECT) continue ;; esac
|
||
pool_vars "$(printf '%s' "$_oe" | tr 'A-Z' 'a-z')"
|
||
case ", $POOL_USE_BASE, " in *", $_mi-my, "*) die "[MY] nodes of $_mi: their entry is the pool $_oe that takes them (a loop)" ;; esac
|
||
done || exit 1
|
||
}
|
||
|
||
# Services (SERVICES="claude ..."): a site or app that always takes its own way, with
|
||
# a group of its own in the dashboard. Per service, keys SVC_<NAME>_* (upper case, - -> _):
|
||
# _GEOSITE geosite lists of MetaCubeX/meta-rules-dat (GEOSITE_URL), e.g. "anthropic"
|
||
# _DOMAINS extra domains (with subdomains), _IPS extra IPs / CIDRs
|
||
# _VIA MY (default): the first alive own server (fallback - the exit IP stays the
|
||
# same while it lives); FOREIGN | RU | DIRECT | MAIN or a pool (its group, e.g. DE):
|
||
# a select starting with it
|
||
# _CHAIN the entry for _VIA = MY or a pool: its servers dial through this (DIRECT, FOREIGN,
|
||
# RU, MY, MY-EXIT or another pool) - "<VIA> ⟶ <CHAIN>" first in the group
|
||
svc_key() { printf 'SVC_%s' "$(printf '%s' "$1" | tr 'a-z-' 'A-Z_')"; }
|
||
|
||
# Pools (POOLS="de wl ..."): own servers and subscription nodes picked by hand, a group each
|
||
# (the name in upper case) for the services' _VIA. Per pool, keys POOL_<NAME>_*:
|
||
# _TYPE fallback (default: the first alive one) | url-test (the fastest) | select (by hand)
|
||
# _SERVERS own servers by name, separated by ";" (names may have spaces)
|
||
# _SUBS providers: a subscription "<id>" (its nodes without [MY]) and/or "<id>-my" (its
|
||
# [MY] nodes), "my-links"; space separated
|
||
# _FILTER, _EXCLUDE mihomo filter / exclude-filter over those providers' nodes (regex; several:
|
||
# separated by `); they never apply to _SERVERS
|
||
# _UPLINK=1 offered in UPLINK (everything connects through this pool first; its own servers and
|
||
# nodes go there directly - group "<POOL> ⟶ DIRECT")
|
||
# A pool left with nothing (servers renamed, subscriptions off) gets REJECT: closed, not elsewhere.
|
||
pool_key() { printf 'POOL_%s' "$(printf '%s' "$1" | tr 'a-z-' 'A-Z_')"; }
|
||
|
||
# pool_vars <name>: POOL_NAME POOL_GROUP POOL_TYPE POOL_PROXIES POOL_USE POOL_FILTER POOL_EXCLUDE
|
||
# for the pool template; ITEM_TAGS pool_proxies / pool_use / pool_filter / pool_exclude /
|
||
# pool_select / pool_urltest; POOL_DROPPED: what is gone from the settings; POOL_JSON: its own
|
||
# servers as JSON strings, one per line (for the chains)
|
||
pool_vars() {
|
||
_k=$(pool_key "$1")
|
||
POOL_NAME=$1
|
||
POOL_GROUP=$(printf '%s' "$1" | tr 'a-z' 'A-Z')
|
||
eval "_t=\${${_k}_TYPE:-fallback} _sv=\${${_k}_SERVERS:-} _su=\${${_k}_SUBS:-} _fi=\${${_k}_FILTER:-} _ex=\${${_k}_EXCLUDE:-}"
|
||
POOL_TYPE=$_t POOL_PROXIES="" POOL_USE="" POOL_DROPPED="" POOL_JSON="" ITEM_TAGS=""
|
||
_old_ifs=$IFS
|
||
IFS=';'
|
||
for _n in $_sv; do
|
||
_n=$(printf '%s' "$_n" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
|
||
[ -n "$_n" ] || continue
|
||
_j="\"$(yq "$_n")\""
|
||
if printf '%s\n' "$OWN_NAMES" | grep -qxF "$_j"; then
|
||
POOL_PROXIES="${POOL_PROXIES:+$POOL_PROXIES, }$(printf '%s' "$_j" | sed 's/\$/\\u0024/g')"
|
||
POOL_JSON="${POOL_JSON:+$POOL_JSON
|
||
}$_j"
|
||
else
|
||
POOL_DROPPED="${POOL_DROPPED:+$POOL_DROPPED, }$_n"
|
||
fi
|
||
done
|
||
IFS=$_old_ifs
|
||
for _p in $_su; do
|
||
case ", $SUB_LIST, $MY_SUB_BASE, " in
|
||
*", $_p, "*) POOL_USE="${POOL_USE:+$POOL_USE, }$_p" ;;
|
||
*) POOL_DROPPED="${POOL_DROPPED:+$POOL_DROPPED, }$_p" ;;
|
||
esac
|
||
done
|
||
# the chains' copies take every [MY] node from <id>-my@<entry>: without the via providers
|
||
POOL_USE_BASE=$POOL_USE
|
||
POOL_USE=$(my_via_expand "$POOL_USE")
|
||
if [ -z "$POOL_PROXIES$POOL_USE" ]; then
|
||
POOL_PROXIES=REJECT
|
||
POOL_TYPE=select
|
||
fi
|
||
POOL_FILTER=$(yq "$_fi") POOL_EXCLUDE=$(yq "$_ex")
|
||
eval "_pfixed=\${${_k}_FIXED:-0}"
|
||
[ "$_pfixed" = 1 ] && ITEM_TAGS="$ITEM_TAGS pool_fixed "
|
||
[ -n "$POOL_PROXIES" ] && ITEM_TAGS="$ITEM_TAGS pool_proxies "
|
||
[ -n "$POOL_USE" ] && ITEM_TAGS="$ITEM_TAGS pool_use "
|
||
[ -n "$POOL_USE" ] && [ -n "$_fi" ] && ITEM_TAGS="$ITEM_TAGS pool_filter "
|
||
[ -n "$POOL_USE" ] && [ -n "$_ex" ] && ITEM_TAGS="$ITEM_TAGS pool_exclude "
|
||
case "$POOL_TYPE" in
|
||
select) ITEM_TAGS="$ITEM_TAGS pool_select " ;;
|
||
url-test) ITEM_TAGS="$ITEM_TAGS pool_urltest " ;;
|
||
esac
|
||
export POOL_NAME POOL_GROUP POOL_TYPE POOL_PROXIES POOL_USE POOL_FILTER POOL_EXCLUDE
|
||
}
|
||
|
||
# check POOLS and their keys; POOL_GROUPS " DE WL " for the services' _VIA
|
||
pools_vars() {
|
||
POOL_GROUPS=" " VARIANTS="" UPLINK_MORE=""
|
||
case "$TAGS" in *" csqtt "*) UPLINK_MORE=", CSQTT" ;; esac
|
||
set -f
|
||
for _s in $POOLS; do
|
||
case "$_s" in [a-z0-9]*) ;; *) die "POOLS: bad name '$_s' (a-z, 0-9, _ -)" ;; esac
|
||
case "$_s" in *[!a-z0-9_-]*) die "POOLS: bad name '$_s' (a-z, 0-9, _ -)" ;; esac
|
||
[ "$(printf '%s\n' $POOLS | grep -cx "$_s")" = 1 ] || die "POOLS: $_s repeats"
|
||
_k=$(pool_key "$_s")
|
||
eval "_t=\${${_k}_TYPE:-fallback} _sv=\${${_k}_SERVERS:-} _su=\${${_k}_SUBS:-}"
|
||
case "$_t" in fallback | url-test | select) ;; *) die "${_k}_TYPE: fallback, url-test or select, not '$_t'" ;; esac
|
||
[ -n "$_sv$_su" ] || die "pool $_s: no SERVERS or SUBS"
|
||
pool_vars "$_s"
|
||
case "$SVC_TAKEN $OVPN_GROUP " in *" $POOL_GROUP "*) die "pool $_s: the group $POOL_GROUP already exists, take another name" ;; esac
|
||
case ", $OWN_LIST, " in *", \"$POOL_GROUP\", "*) die "pool $_s: an own server is named $POOL_GROUP" ;; esac
|
||
[ -z "$POOL_DROPPED" ] || log "warning: pool $_s: no longer in the settings: $POOL_DROPPED"
|
||
[ "$POOL_PROXIES" != REJECT ] || log "warning: pool $_s is empty: its services are closed (REJECT)"
|
||
POOL_GROUPS="$POOL_GROUPS$POOL_GROUP "
|
||
eval "_u=\${${_k}_UPLINK:-0}"
|
||
if [ "$_u" = 1 ]; then
|
||
variant_add "$POOL_GROUP" DIRECT
|
||
UPLINK_MORE="$UPLINK_MORE, \"$POOL_GROUP ⟶ DIRECT\""
|
||
fi
|
||
done
|
||
set +f
|
||
ITEM_TAGS=""
|
||
export UPLINK_MORE
|
||
}
|
||
|
||
# Chains: "<pool> ⟶ <entry>" - the pool's own servers and subscription nodes, each dialing
|
||
# through <entry> (DIRECT, FOREIGN, RU, MY, MY-EXIT or another pool) instead of what they use
|
||
# otherwise. mihomo chains only by a proxy's dialer-proxy, so these are copies: own servers
|
||
# "<server> ⟶ <entry>" (proxies/35-variant), file providers "<provider>@<entry>" on the same
|
||
# downloaded file (providers/19-vprov), the group (groups/47-vgroup). <pool> = MY: all own servers
|
||
# and [MY] nodes. VARIANTS: "<pool>|<entry>" lines.
|
||
variant_add() {
|
||
printf '%s\n' "$VARIANTS" | grep -qxF "$1|$2" || VARIANTS="${VARIANTS:+$VARIANTS
|
||
}$1|$2"
|
||
}
|
||
|
||
# variant_members <pool group>: _vm_json (own servers, JSON strings per line), _vm_use ("a, b"),
|
||
# _vm_type, _vm_filter, _vm_exclude
|
||
variant_members() {
|
||
_pfixed=0
|
||
if [ "$1" = MY ]; then
|
||
_vm_json=$OWN_NAMES _vm_use=$MY_SUB_BASE _vm_type=fallback _vm_filter="" _vm_exclude=""
|
||
else
|
||
pool_vars "$(printf '%s' "$1" | tr 'A-Z' 'a-z')"
|
||
_vm_json=$POOL_JSON _vm_use=$POOL_USE_BASE _vm_type=$POOL_TYPE _vm_filter=$POOL_FILTER _vm_exclude=$POOL_EXCLUDE
|
||
if [ "$_pfixed" = 1 ] && [ -n "$_fi" ] && [ -n "${VM_ENTRY:-}" ]; then
|
||
_vm_filter=$(yq "${_fi%\$} ⟶ $VM_ENTRY\$")
|
||
fi
|
||
fi
|
||
}
|
||
|
||
# VARIANTS -> VARIANT_PROXIES (copies of own servers, once per server and entry), VPROV_ITEMS
|
||
# ("<provider>|<entry>", once each), VGROUP_ITEMS (= VARIANTS); tags variant / vprov / vgroup
|
||
variants_build() {
|
||
VARIANT_PROXIES="" VPROV_ITEMS="" VGROUP_ITEMS=$VARIANTS
|
||
_out=$(mktemp)
|
||
printf '%s\n' "$VARIANTS" | while IFS='|' read -r _p _e; do
|
||
[ -n "$_p" ] || continue
|
||
variant_members "$_p"
|
||
printf '%s\n' "$_vm_json" | while IFS= read -r _j; do
|
||
[ -n "$_j" ] || continue
|
||
_jc=$(printf '%s' "$_j" | sed 's/\$/\\u0024/g')
|
||
# through the environment: awk -v would read the backslashes of the JSON name
|
||
_b=$(printf '%s\n' "$OWN_BODIES" | P="\"name\":$_jc," awk 'index($0, ENVIRON["P"]) == 1 { print; exit }')
|
||
[ -n "$_b" ] || continue
|
||
_rest=${_b#"\"name\":$_jc"}
|
||
_n="${_jc%\"} ⟶ $_e\""
|
||
if [ "$_e" = DIRECT ]; then
|
||
printf '%s\n' "- {\"name\":$_n$_rest"
|
||
else
|
||
printf '%s\n' "- {\"dialer-proxy\": \"$_e\", \"name\":$_n$_rest"
|
||
fi
|
||
done
|
||
done | awk '!seen[$0]++' > "$_out"
|
||
VARIANT_PROXIES=$(cat "$_out")
|
||
printf '%s\n' "$VARIANTS" | while IFS='|' read -r _p _e; do
|
||
[ -n "$_p" ] || continue
|
||
variant_members "$_p"
|
||
printf '%s\n' "$_vm_use" | tr ',' '\n' | sed 's/^ *//' | while read -r _v; do
|
||
[ -n "$_v" ] && printf '%s|%s\n' "$_v" "$_e"
|
||
done
|
||
done | awk '!seen[$0]++' > "$_out"
|
||
VPROV_ITEMS=$(cat "$_out")
|
||
rm -f "$_out"
|
||
[ -n "$VARIANT_PROXIES" ] && TAGS="$TAGS variant "
|
||
[ -n "$VPROV_ITEMS" ] && TAGS="$TAGS vprov "
|
||
[ -n "$VGROUP_ITEMS" ] && TAGS="$TAGS vgroup "
|
||
export VARIANT_PROXIES
|
||
}
|
||
|
||
# vprov_vars "<provider>|<entry>": VP_NAME VP_BASE VP_ENTRY VP_PATH (+ the subscription's
|
||
# SUB_* for the phone); ITEM_TAGS vp_sub / vp_my / vp_links, vp_direct
|
||
vprov_vars() {
|
||
VP_BASE=${1%%|*} VP_ENTRY=${1#*|}
|
||
VP_NAME="$VP_BASE@$VP_ENTRY"
|
||
ITEM_TAGS=""
|
||
[ "$VP_ENTRY" = DIRECT ] && ITEM_TAGS=" vp_direct "
|
||
case "$VP_BASE" in
|
||
my-links) VP_PATH=./providers/my-links.txt ITEM_TAGS="$ITEM_TAGS vp_links " ;;
|
||
*-my) VP_PATH="./providers/${VP_BASE%-my}.yaml" ITEM_TAGS="$ITEM_TAGS vp_my " ;;
|
||
*) VP_PATH="./providers/$VP_BASE.yaml" ITEM_TAGS="$ITEM_TAGS vp_sub " ;;
|
||
esac
|
||
# the phone downloads it again (see providers/15-sub): the subscription's URL and headers
|
||
_id=${VP_BASE%-my} _i=0
|
||
for _pr in $SUB_PAIRS; do
|
||
[ "${_pr%%=*}" = "$_id" ] && sub_vars "$_i" "$_id" "${_pr#*=}"
|
||
_i=$((_i + 1))
|
||
done
|
||
export VP_NAME VP_BASE VP_ENTRY VP_PATH
|
||
}
|
||
|
||
# vgroup_vars "<pool>|<entry>": VG_* for groups/47-vgroup; ITEM_TAGS vg_*
|
||
vgroup_vars() {
|
||
VG_POOL=${1%%|*} VG_ENTRY=${1#*|}
|
||
VG_NAME="$VG_POOL ⟶ $VG_ENTRY"
|
||
VM_ENTRY=$VG_ENTRY
|
||
variant_members "$VG_POOL"
|
||
VM_ENTRY=""
|
||
VG_TYPE=$_vm_type VG_FILTER=$_vm_filter VG_EXCLUDE=$_vm_exclude
|
||
VG_FIXED=${_pfixed:-0}
|
||
VG_PROXIES=$(printf '%s\n' "$_vm_json" | while IFS= read -r _j; do
|
||
[ -n "$_j" ] && printf '%s\n' "${_j%\"} ⟶ $VG_ENTRY\""
|
||
done | sed 's/\$/\\u0024/g' | awk '{ printf "%s%s", (NR > 1 ? ", " : ""), $0 }')
|
||
VG_USE=$(printf '%s\n' "$_vm_use" | tr ',' '\n' | sed 's/^ *//' | grep . | sed "s/\$/@$VG_ENTRY/" |
|
||
awk '{ printf "%s%s", (NR > 1 ? ", " : ""), $0 }')
|
||
if [ -z "$VG_PROXIES$VG_USE" ]; then
|
||
VG_PROXIES=REJECT VG_TYPE=select
|
||
fi
|
||
ITEM_TAGS=""
|
||
[ "$VG_FIXED" = 1 ] && ITEM_TAGS="$ITEM_TAGS vg_fixed "
|
||
[ -n "$VG_PROXIES" ] && ITEM_TAGS="$ITEM_TAGS vg_proxies "
|
||
[ -n "$VG_USE" ] && ITEM_TAGS="$ITEM_TAGS vg_use "
|
||
[ -n "$VG_USE" ] && [ -n "$VG_FILTER" ] && ITEM_TAGS="$ITEM_TAGS vg_filter "
|
||
[ -n "$VG_USE" ] && [ -n "$VG_EXCLUDE" ] && ITEM_TAGS="$ITEM_TAGS vg_exclude "
|
||
case "$VG_TYPE" in
|
||
select) ITEM_TAGS="$ITEM_TAGS vg_select " ;;
|
||
url-test) ITEM_TAGS="$ITEM_TAGS vg_urltest " ;;
|
||
esac
|
||
export VG_POOL VG_ENTRY VG_NAME VG_TYPE VG_PROXIES VG_USE VG_FILTER VG_EXCLUDE
|
||
}
|
||
|
||
# names of the groups and proxies a service or pool group must not take
|
||
SVC_TAKEN=" BOOT BOOT-AUTO RU FOREIGN TORRENT TORRENT-SEL MY MY-EXIT MAIN PUSH UPLINK TAILSCALE TS-EXIT OVPN-EXIT CSQTT DIRECT REJECT REJECT-DROP PASS COMPATIBLE GLOBAL "
|
||
|
||
# A fixed service gets an internal one-node pool. Its identity is settings, not
|
||
# cache.db. This reuses pool/variant rendering for profile-specific dialer-proxy.
|
||
# Called before pools_vars; generated keys exist only in this render's subshell.
|
||
services_fixed_vars() {
|
||
set -f
|
||
for _fs in $SERVICES; do
|
||
case "$_fs" in '' | *[!a-z0-9_-]*) die "SERVICES: bad name '$_fs'" ;; esac
|
||
_fk=$(svc_key "$_fs")
|
||
eval "_fn=\${${_fk}_SERVER:-} _fp=\${${_fk}_PROVIDER:-}"
|
||
[ -n "$_fn" ] || {
|
||
[ -z "$_fp" ] || die "${_fk}_PROVIDER: SERVER is empty"
|
||
continue
|
||
}
|
||
case "$_fn" in *';'* | *'
|
||
'*) die "${_fk}_SERVER: semicolon/newline is not supported" ;; esac
|
||
case "$_fp" in *[!A-Za-z0-9_-]*) die "${_fk}_PROVIDER: bad provider id" ;; esac
|
||
_fpool="svc-fixed-$_fs"
|
||
case " $POOLS " in *" $_fpool "*) die "pool $_fpool is reserved for service $_fs" ;; esac
|
||
_fpk=$(pool_key "$_fpool")
|
||
for _existing in $POOLS; do
|
||
[ "$(pool_key "$_existing")" != "$_fpk" ] || die "pool $_existing conflicts with fixed service $_fs"
|
||
done
|
||
TAGS="$TAGS pool "
|
||
POOLS="${POOLS:+$POOLS }$_fpool"
|
||
eval "${_fpk}_TYPE=select ${_fpk}_FIXED=1"
|
||
if [ -n "$_fp" ]; then
|
||
# Literal, anchored regex. Backtick separates filters in mihomo, so encode it.
|
||
_fregex=$(printf '%s' "$_fn" | sed 's/[][\\.^$*+?(){}|]/\\&/g; s/`/\\x60/g')
|
||
_fregex="^$_fregex\$"
|
||
eval "${_fpk}_SUBS=\$_fp ${_fpk}_FILTER=\$_fregex ${_fpk}_SERVERS=''"
|
||
else
|
||
eval "${_fpk}_SERVERS=\$_fn ${_fpk}_SUBS='' ${_fpk}_FILTER=''"
|
||
fi
|
||
done
|
||
set +f
|
||
}
|
||
|
||
# hostlist_payload <files>: zapret-style hostlists (a domain per line, "# comment", ".gz" too)
|
||
# -> the payload of an inline rule-provider (behavior: domain), deduplicated: "+.a.com"
|
||
# (with subdomains, as zapret matches), "^b.com" -> "b.com" (zapret: this domain only);
|
||
# IP lines and junk are dropped; files that are not there are skipped (services_vars warns)
|
||
hostlist_payload() {
|
||
set -f
|
||
for _f in $1; do
|
||
[ -f "$_f" ] && [ -r "$_f" ] || continue
|
||
case "$_f" in *.gz) gzip -dc "$_f" 2>/dev/null ;; *) cat "$_f" ;; esac
|
||
echo
|
||
done | awk '{
|
||
sub(/#.*/, ""); gsub(/[ \t\r]/, ""); $0 = tolower($0)
|
||
exact = sub(/^\^/, "")
|
||
sub(/^\*/, ""); sub(/^\+/, ""); sub(/^\./, ""); sub(/\.$/, "")
|
||
if ($0 !~ /^[a-z0-9_-]+(\.[a-z0-9_-]+)*$/ || $0 ~ /^[0-9.]+$/) next
|
||
d = (exact ? "" : "+.") $0
|
||
if (!(d in seen)) { seen[d] = 1; print d }
|
||
}'
|
||
set +f
|
||
}
|
||
|
||
# svc_vars <name>: SVC_NAME SVC_GROUP SVC_GEOSITE SVC_DOMAINS SVC_IPS SVC_VIA SVC_PROXIES
|
||
# SVC_HOSTLIST (the payload of hostlist-<name>, hostlist_payload) for the svc templates;
|
||
# ITEM_TAGS " svc_my " when the service goes through own servers, + " svc_hostlist "
|
||
svc_vars() {
|
||
_k=$(svc_key "$1")
|
||
SVC_NAME=$1
|
||
SVC_GROUP=$(printf '%s' "$1" | tr 'a-z' 'A-Z')
|
||
eval "SVC_GEOSITE=\${${_k}_GEOSITE:-} SVC_DOMAINS=\${${_k}_DOMAINS:-} SVC_IPS=\${${_k}_IPS:-} SVC_VIA=\${${_k}_VIA:-MY} SVC_CHAIN=\${${_k}_CHAIN:-}"
|
||
eval "SVC_HOSTLIST_FILES=\${${_k}_HOSTLIST:-}"
|
||
SVC_HOSTLIST=""
|
||
[ -z "$SVC_HOSTLIST_FILES" ] || SVC_HOSTLIST=$(hostlist_payload "$SVC_HOSTLIST_FILES")
|
||
eval "SVC_SERVER=\${${_k}_SERVER:-}"
|
||
[ -z "$SVC_SERVER" ] || SVC_VIA="SVC-FIXED-$(printf '%s' "$1" | tr 'a-z' 'A-Z')"
|
||
SVC_DOMAINS=$(norm_list dom "$SVC_DOMAINS")
|
||
SVC_IPS=$(norm_list ip "$SVC_IPS")
|
||
SVC_PROXIES=$SVC_VIA
|
||
for _g in MY FOREIGN RU DIRECT; do
|
||
[ "$_g" = "$SVC_VIA" ] || SVC_PROXIES="$SVC_PROXIES, $_g"
|
||
done
|
||
ITEM_TAGS=""
|
||
if [ -n "$SVC_CHAIN" ]; then
|
||
SVC_PROXIES="\"$SVC_VIA ⟶ $SVC_CHAIN\", $SVC_PROXIES"
|
||
elif [ "$SVC_VIA" = MY ]; then
|
||
ITEM_TAGS=" svc_my "
|
||
fi
|
||
if [ -n "$SVC_SERVER" ]; then
|
||
# One allowed destination: ignore cached selections from the old group.
|
||
SVC_PROXIES="\"$SVC_VIA\""
|
||
[ -z "$SVC_CHAIN" ] || SVC_PROXIES="\"$SVC_VIA ⟶ $SVC_CHAIN\""
|
||
fi
|
||
[ -z "$SVC_HOSTLIST" ] || ITEM_TAGS="${ITEM_TAGS:- }svc_hostlist "
|
||
export SVC_NAME SVC_GROUP SVC_GEOSITE SVC_DOMAINS SVC_IPS SVC_PROXIES SVC_HOSTLIST
|
||
}
|
||
|
||
# check SERVICES and their keys; GEOSITE_ITEMS: the geosite lists of all services, once each
|
||
services_vars() {
|
||
GEOSITE_ITEMS=""
|
||
set -f
|
||
for _s in $SERVICES; do
|
||
case "$_s" in [a-z0-9]*) ;; *) die "SERVICES: bad name '$_s' (a-z, 0-9, _ -)" ;; esac
|
||
case "$_s" in *[!a-z0-9_-]*) die "SERVICES: bad name '$_s' (a-z, 0-9, _ -)" ;; esac
|
||
[ "$(printf '%s\n' $SERVICES | grep -cx "$_s")" = 1 ] || die "SERVICES: $_s repeats"
|
||
svc_vars "$_s"
|
||
case "$SVC_TAKEN $OVPN_GROUP$POOL_GROUPS" in *" $SVC_GROUP "*) die "service $_s: the group $SVC_GROUP already exists, take another name" ;; esac
|
||
case ", $OWN_LIST, " in *", \"$SVC_GROUP\", "*) die "service $_s: an own server is named $SVC_GROUP" ;; esac
|
||
case " MY FOREIGN RU DIRECT MAIN$POOL_GROUPS" in
|
||
*" $SVC_VIA "*) ;;
|
||
*) die "$(svc_key "$_s")_VIA: MY, FOREIGN, RU, DIRECT, MAIN or a pool${POOL_GROUPS% }, not '$SVC_VIA'" ;;
|
||
esac
|
||
[ -n "$SVC_GEOSITE$SVC_DOMAINS$SVC_IPS$SVC_HOSTLIST_FILES" ] || die "service $_s: no GEOSITE, DOMAINS, IPS or HOSTLIST"
|
||
for _f in $SVC_HOSTLIST_FILES; do
|
||
[ -f "$_f" ] && [ -r "$_f" ] || log "warning: $(svc_key "$_s")_HOSTLIST: no file $_f, skipped"
|
||
done
|
||
[ -z "$SVC_HOSTLIST_FILES" ] || [ -n "$SVC_HOSTLIST" ] ||
|
||
log "warning: $(svc_key "$_s")_HOSTLIST: no domains in $SVC_HOSTLIST_FILES"
|
||
if [ -n "$SVC_CHAIN" ]; then
|
||
case " MY$POOL_GROUPS" in *" $SVC_VIA "*) ;; *) die "$(svc_key "$_s")_CHAIN: only for _VIA = MY or a pool" ;; esac
|
||
_entries=" DIRECT FOREIGN RU MY${POOL_GROUPS% }"
|
||
case "$TAGS" in *" my_exit "*) _entries="$_entries MY-EXIT" ;; esac
|
||
case "$_entries " in *" $SVC_CHAIN "*) ;; *) die "$(svc_key "$_s")_CHAIN: one of$_entries, not '$SVC_CHAIN'" ;; esac
|
||
[ "$SVC_CHAIN" != "$SVC_VIA" ] || die "$(svc_key "$_s")_CHAIN: the same as _VIA"
|
||
variant_add "$SVC_VIA" "$SVC_CHAIN"
|
||
fi
|
||
for _g in $SVC_GEOSITE; do
|
||
case "$_g" in *[!a-z0-9._@!-]*) die "service $_s: bad geosite name '$_g'" ;; esac
|
||
case " $GEOSITE_ITEMS " in *" $_g "*) ;; *) GEOSITE_ITEMS="${GEOSITE_ITEMS:+$GEOSITE_ITEMS }$_g" ;; esac
|
||
done
|
||
done
|
||
set +f
|
||
ITEM_TAGS=""
|
||
}
|
||
|
||
render_file() {
|
||
awk -v tags="$TAGS${ITEM_TAGS:-}" '
|
||
function active(c, neg) {
|
||
neg = 0
|
||
if (substr(c, 1, 1) == "!") { neg = 1; c = substr(c, 2) }
|
||
return (index(tags, " " c " ") > 0) != neg
|
||
}
|
||
function subst(s, out, i, j) {
|
||
out = ""
|
||
while ((i = index(s, "${")) > 0) {
|
||
j = index(substr(s, i + 2), "}")
|
||
if (j == 0) break
|
||
out = out substr(s, 1, i - 1) ENVIRON[substr(s, i + 2, j - 1)]
|
||
s = substr(s, i + 2 + j)
|
||
}
|
||
return out s
|
||
}
|
||
{
|
||
line = $0
|
||
if ((p = index(line, "#@")) > 0) {
|
||
n = split(substr(line, p + 2), cs, ",")
|
||
line = substr(line, 1, p - 1)
|
||
sub(/[ \t]+$/, "", line)
|
||
for (k = 1; k <= n; k++) if (!active(cs[k])) next
|
||
}
|
||
if ((i = index(line, "${@@")) > 0) {
|
||
j = index(substr(line, i + 4), "}")
|
||
pre = substr(line, 1, i - 1)
|
||
post = substr(line, i + 4 + j)
|
||
n = split(ENVIRON[substr(line, i + 4, j - 1)], ws, "\n")
|
||
for (k = 1; k <= n; k++) if (ws[k] != "") print subst(pre ws[k] post)
|
||
next
|
||
}
|
||
if ((i = index(line, "${@")) > 0) {
|
||
j = index(substr(line, i + 3), "}")
|
||
pre = substr(line, 1, i - 1)
|
||
post = substr(line, i + 3 + j)
|
||
n = split(ENVIRON[substr(line, i + 3, j - 1)], ws, /[ \t\n]+/)
|
||
for (k = 1; k <= n; k++) if (ws[k] != "") print subst(pre ws[k] post)
|
||
next
|
||
}
|
||
print subst(line)
|
||
}' "$1"
|
||
}
|
||
|
||
# is "<module>.<tag>...[.each]" active? sets EACH
|
||
fragment_active() {
|
||
EACH=0
|
||
_mod=${1%%.*}
|
||
case "$TAGS" in *" $_mod "*) ;; *) return 1 ;; esac
|
||
_rest=${1#"$_mod"}
|
||
_old_ifs=$IFS
|
||
IFS=.
|
||
for _t in $_rest; do
|
||
[ -z "$_t" ] && continue
|
||
if [ "$_t" = each ]; then EACH=1; continue; fi
|
||
case "$TAGS" in *" $_t "*) ;; *) IFS=$_old_ifs; return 1 ;; esac
|
||
done
|
||
IFS=$_old_ifs
|
||
return 0
|
||
}
|
||
|
||
# render_part <file>: append the rendered file to _out (render_section)
|
||
render_part() {
|
||
_part=$(render_file "$1")
|
||
[ -n "$_part" ] && _out="${_out:+$_out
|
||
|
||
}$_part"
|
||
}
|
||
|
||
render_section() {
|
||
_out=""
|
||
for f in "$TPL_DIR/$1"/*.yaml; do
|
||
[ -f "$f" ] || continue
|
||
_name=${f##*/}
|
||
_name=${_name%.yaml}
|
||
fragment_active "${_name#*-}" || continue
|
||
if [ "$EACH" = 1 ] && [ "$_mod" = boot ]; then
|
||
for _it in $SEED_ITEMS; do
|
||
seed_vars "$_it"
|
||
render_part "$f"
|
||
done
|
||
elif [ "$EACH" = 1 ] && [ "$_mod" = pool ]; then
|
||
for _it in $POOLS; do
|
||
pool_vars "$_it"
|
||
render_part "$f"
|
||
done
|
||
ITEM_TAGS=""
|
||
elif [ "$EACH" = 1 ] && { [ "$_mod" = vprov ] || [ "$_mod" = vgroup ]; }; then
|
||
# items have spaces ("a|b" per line): split on lines only
|
||
_old_ifs=$IFS
|
||
IFS='
|
||
'
|
||
for _it in $([ "$_mod" = vprov ] && printf '%s\n' "$VPROV_ITEMS" || printf '%s\n' "$VGROUP_ITEMS"); do
|
||
IFS=$_old_ifs
|
||
if [ "$_mod" = vprov ]; then vprov_vars "$_it"; else vgroup_vars "$_it"; fi
|
||
render_part "$f"
|
||
done
|
||
IFS=$_old_ifs
|
||
ITEM_TAGS=""
|
||
elif [ "$EACH" = 1 ] && [ "$_mod" = myvia ]; then
|
||
for _it in $MYVIA_ITEMS; do
|
||
myvia_vars "$_it"
|
||
render_part "$f"
|
||
done
|
||
elif [ "$EACH" = 1 ] && [ "$_mod" = svc ]; then
|
||
for _it in $SERVICES; do
|
||
svc_vars "$_it"
|
||
render_part "$f"
|
||
done
|
||
ITEM_TAGS=""
|
||
elif [ "$EACH" = 1 ] && [ "$_mod" = geosite ]; then
|
||
for GEOSITE_NAME in $GEOSITE_ITEMS; do
|
||
export GEOSITE_NAME
|
||
render_part "$f"
|
||
done
|
||
elif [ "$EACH" = 1 ]; then
|
||
i=0
|
||
for _pr in $SUB_PAIRS; do
|
||
if ! sub_off "$i" "${_pr%%=*}"; then
|
||
sub_vars "$i" "${_pr%%=*}" "${_pr#*=}"
|
||
render_part "$f"
|
||
fi
|
||
i=$((i + 1))
|
||
done
|
||
else
|
||
render_part "$f"
|
||
fi
|
||
done
|
||
[ -n "$_out" ] || return 0
|
||
[ -n "${2:-}" ] && printf "%s\n" "$2"
|
||
printf "%s\n" "$_out"
|
||
}
|
||
|
||
# own lists of the settings (templates/rules/40-base.yaml): norm_list dom|ip <words>
|
||
# dom: "*.a.com +.b.com .c.com" -> "a.com b.com c.com" (DOMAIN-SUFFIX covers subdomains)
|
||
# ip: "1.2.3.4" -> "1.2.3.4/32", "2001:db8::1" -> "2001:db8::1/128"
|
||
norm_list() {
|
||
set -f
|
||
_o=""
|
||
for _w in $2; do
|
||
case "$1" in
|
||
dom) _w=${_w#\*} _w=${_w#+} _w=${_w#.} ;;
|
||
*) case "$_w" in */*) ;; *:*) _w=$_w/128 ;; *) _w=$_w/32 ;; esac ;;
|
||
esac
|
||
[ -n "$_w" ] && _o="${_o:+$_o }$_w"
|
||
done
|
||
set +f
|
||
printf '%s' "$_o"
|
||
}
|
||
|
||
# LOCAL_HOSTS "a.com=192.168.1.10 b.org=10.0.0.5" (a domain with its subdomains ->
|
||
# a LAN address; router only) -> LOCAL_DOMAINS "a.com b.org" and LOCAL_HOSTS_YAML,
|
||
# the lines of the hosts: section
|
||
local_hosts_vars() {
|
||
LOCAL_DOMAINS="" LOCAL_HOSTS_YAML=""
|
||
case "$TAGS" in *" local_hosts "*) ;; *) return 0 ;; esac
|
||
set -f
|
||
for _w in $LOCAL_HOSTS; do
|
||
_d=${_w%%=*} _a=${_w#*=}
|
||
_d=${_d#\*} _d=${_d#+} _d=${_d#.}
|
||
case "$_w" in *=*) ;; *) die "LOCAL_HOSTS: '$_w' is not domain=address" ;; esac
|
||
case "$_d" in '' | *[!A-Za-z0-9.-]*) die "LOCAL_HOSTS: bad domain in '$_w'" ;; esac
|
||
case "$_a" in '' | *[!0-9A-Fa-f.:]*) die "LOCAL_HOSTS: bad address in '$_w'" ;; esac
|
||
LOCAL_DOMAINS="${LOCAL_DOMAINS:+$LOCAL_DOMAINS }$_d"
|
||
LOCAL_HOSTS_YAML="${LOCAL_HOSTS_YAML:+$LOCAL_HOSTS_YAML
|
||
}'+.$_d': $_a"
|
||
done
|
||
set +f
|
||
}
|
||
|
||
# is_local_url <url>: its host is one of LOCAL_DOMAINS or under one
|
||
is_local_url() {
|
||
[ -n "${LOCAL_DOMAINS:-}" ] || return 1
|
||
# own names: sub_vars, the caller, uses _h and _d
|
||
_lu=${1#*://}
|
||
_lu=${_lu%%/*} _lu=${_lu%%\?*} _lu=${_lu##*@} _lu=${_lu%:*}
|
||
for _ld in $LOCAL_DOMAINS; do
|
||
case "$_lu" in "$_ld" | *".$_ld") return 0 ;; esac
|
||
done
|
||
return 1
|
||
}
|
||
|
||
render() {
|
||
set_defaults
|
||
sub_pairs
|
||
boot_seeds
|
||
check_vars
|
||
own_servers_vars
|
||
compute_tags
|
||
for _l in RU_IPS FOREIGN_IPS MY_IPS; do eval "$_l=\$(norm_list ip \"\$$_l\")"; done
|
||
for _l in RU_DOMAINS FOREIGN_DOMAINS MY_DOMAINS; do eval "$_l=\$(norm_list dom \"\$$_l\")"; done
|
||
# after compute_tags: pools use SUB_LIST / MY_SUB_LIST
|
||
my_node_vars
|
||
services_fixed_vars
|
||
pools_vars
|
||
own_entries_check
|
||
services_vars
|
||
[ -n "$GEOSITE_ITEMS" ] && TAGS="$TAGS geosite "
|
||
variants_build
|
||
local_hosts_vars
|
||
export TARGET LOCATION RULESET_URL BOOT_SERVER BOOT_PORT BOOT_UUID BOOT_SNI \
|
||
BOOT_PBK BOOT_SID TS_HOSTNAME TS_DOMAINS OVPN_PROVIDER OVPN_GROUP OVPN_SERVER_HOST \
|
||
OVPN_SERVER_IPS OVPN_ROUTES OVPN_CHECK_URL TS_CHECK_URL CSQTT_IFACE CSQTT_PROCESS \
|
||
RU_IPS FOREIGN_IPS MY_IPS RU_DOMAINS FOREIGN_DOMAINS MY_DOMAINS LOCAL_DOMAINS LOCAL_HOSTS_YAML \
|
||
OWN_PLAIN OWN_ENTRY OWN_LIST GEOSITE_URL
|
||
_first=1
|
||
for s in head proxies:proxies providers:proxy-providers rule-providers:rule-providers sniffer dns \
|
||
groups:proxy-groups rules:rules; do
|
||
_dir=${s%%:*}
|
||
_hdr=""
|
||
[ "$_dir" != "$s" ] && _hdr="${s#*:}:"
|
||
_sec=$(render_section "$_dir" "$_hdr")
|
||
[ -n "$_sec" ] || continue
|
||
[ "$_first" = 1 ] || echo
|
||
printf "%s\n" "$_sec"
|
||
_first=0
|
||
done
|
||
}
|
||
|
||
load_env() {
|
||
for e in "$@"; do
|
||
[ -f "$e" ] || die "no env file $e"
|
||
set -a
|
||
. "$e"
|
||
set +a
|
||
done
|
||
}
|
||
|
||
cmd_render() {
|
||
[ $# -gt 0 ] || die "usage: render <env>..."
|
||
load_env "$@"
|
||
render
|
||
}
|
||
|
||
# OpenVPN routes for the rule-provider <OVPN_PROVIDER>-routes (templates/rule-providers):
|
||
# <name>.all - the list (ovpn.sh on puts it back), <name>.yaml - what mihomo
|
||
# reads: the list, or empty while the tunnel should be off (manual off, timer,
|
||
# schedule: ovpn.sh want)
|
||
# own servers as links (MY_LINKS) -> run/providers/my-links.txt, one per line, for the
|
||
# file provider my-links (templates/providers): mihomo itself parses them like a
|
||
# subscription. Holds secrets: 600. No links -> no file.
|
||
my_links_write() {
|
||
(
|
||
[ -f "$PROFILES_D/common.env" ] && load_env "$PROFILES_D/common.env"
|
||
set_defaults
|
||
_f=$NIKKI_DIR/run/providers/my-links.txt
|
||
if [ -z "$MY_LINKS" ]; then
|
||
rm -f "$_f"
|
||
exit 0
|
||
fi
|
||
mkdir -p "${_f%/*}"
|
||
umask 077
|
||
set -f
|
||
printf '%s\n' $MY_LINKS > "$_f.tmp" && mv "$_f.tmp" "$_f"
|
||
)
|
||
}
|
||
|
||
ovpn_routes_write() {
|
||
(
|
||
[ -f "$PROFILES_D/common.env" ] && load_env "$PROFILES_D/common.env"
|
||
set_defaults
|
||
_r=$NIKKI_DIR/run/providers/$OVPN_PROVIDER-routes
|
||
mkdir -p "${_r%/*}"
|
||
printf '%s\n' $OVPN_ROUTES > "$_r.all"
|
||
_on=1
|
||
if command -v ovpn.sh >/dev/null 2>&1; then
|
||
ovpn.sh want 2>/dev/null || _on=0
|
||
elif [ -f "$NIKKI_DIR/openvpn.off" ]; then
|
||
_on=0
|
||
fi
|
||
if [ "$_on" = 0 ] || [ -z "$OVPN_ROUTES" ]; then
|
||
echo 'payload: []'
|
||
else
|
||
echo 'payload:'
|
||
for _n in $OVPN_ROUTES; do echo " - '$_n'"; done
|
||
fi > "$_r.yaml"
|
||
)
|
||
}
|
||
|
||
cmd_build() {
|
||
[ -d "$PROFILES_D" ] || die "no $PROFILES_D (see profile.env.example)"
|
||
mkdir -p "$PROFILES_OUT"
|
||
# before mihomo -t: the profiles reference these files
|
||
ovpn_routes_write
|
||
my_links_write
|
||
if [ $# -eq 0 ]; then
|
||
for e in "$PROFILES_D"/*.env; do
|
||
n=${e##*/}
|
||
n=${n%.env}
|
||
[ "$n" = common ] || set -- "$@" "$n"
|
||
done
|
||
fi
|
||
for n in "$@"; do
|
||
out="$PROFILES_OUT/$n.yaml"
|
||
envs="$PROFILES_D/$n.env"
|
||
[ -f "$PROFILES_D/common.env" ] && envs="$PROFILES_D/common.env $envs"
|
||
# subshell: profiles must not leak variables into each other
|
||
# shellcheck disable=SC2086
|
||
if (cmd_render $envs) > "$out.tmp"; then
|
||
mv "$out.tmp" "$out"
|
||
log "built $out"
|
||
if command -v mihomo >/dev/null 2>&1; then
|
||
mihomo -t -d "$NIKKI_DIR/run" -f "$out" >/dev/null 2>&1 ||
|
||
log "warning: mihomo -t failed for $out (run: mihomo -t -d $NIKKI_DIR/run -f $out)"
|
||
fi
|
||
else
|
||
rm -f "$out.tmp"
|
||
die "build of $n failed"
|
||
fi
|
||
done
|
||
# yaml whose env file is gone (renamed or removed profile)
|
||
for _y in "$PROFILES_OUT"/*.yaml; do
|
||
[ -f "$_y" ] || continue
|
||
_n=${_y##*/}
|
||
[ -f "$PROFILES_D/${_n%.yaml}.env" ] || { rm -f "$_y"; log "removed stale $_y"; }
|
||
done
|
||
build_mobile
|
||
}
|
||
|
||
# Phone config (an app on the mihomo core: FlClash, Clash Mi, ...): with MOBILE=1 in common.env, common.env rendered with
|
||
# TARGET=mobile is served by uhttpd as /mihomo-kit/<token>.yaml (subscription
|
||
# links inside: the token is the secret, "mobile new" replaces it).
|
||
MOBILE_DIR=/www/mihomo-kit
|
||
build_mobile() {
|
||
if ! grep -q '^MOBILE=1' "$PROFILES_D/common.env" 2>/dev/null || [ ! -d /www ]; then
|
||
rm -f "$MOBILE_DIR"/*.yaml
|
||
return 0
|
||
fi
|
||
if [ ! -s "$KIT_DIR/mobile-token" ]; then
|
||
(umask 077; head -c 16 /dev/urandom | md5sum | cut -c1-32 > "$KIT_DIR/mobile-token")
|
||
fi
|
||
_tok=$(cat "$KIT_DIR/mobile-token")
|
||
mkdir -p "$MOBILE_DIR"
|
||
chmod 755 "$MOBILE_DIR"
|
||
# no directory listing of the tokens
|
||
[ -f "$MOBILE_DIR/index.html" ] || : > "$MOBILE_DIR/index.html"
|
||
echo TARGET=mobile > /tmp/mihomo-kit-mobile.env
|
||
if (cmd_render "$PROFILES_D/common.env" /tmp/mihomo-kit-mobile.env) > "$MOBILE_DIR/$_tok.yaml.tmp"; then
|
||
for _f in "$MOBILE_DIR"/*.yaml; do
|
||
[ "$_f" = "$MOBILE_DIR/$_tok.yaml" ] || rm -f "$_f"
|
||
done
|
||
mv "$MOBILE_DIR/$_tok.yaml.tmp" "$MOBILE_DIR/$_tok.yaml"
|
||
chmod 644 "$MOBILE_DIR/$_tok.yaml"
|
||
log "built phone config /mihomo-kit/$_tok.yaml"
|
||
else
|
||
rm -f "$MOBILE_DIR/$_tok.yaml.tmp"
|
||
log "warning: phone config build failed"
|
||
fi
|
||
rm -f /tmp/mihomo-kit-mobile.env
|
||
}
|
||
|
||
cmd_mobile() {
|
||
[ "${1:-}" = new ] || die "usage: mobile new"
|
||
rm -f "$KIT_DIR/mobile-token"
|
||
build_mobile
|
||
}
|
||
|
||
# profile_val <name> <KEY>: KEY of a profile (common.env, overridden by <name>.env)
|
||
profile_val() {
|
||
cat "$PROFILES_D/common.env" "$PROFILES_D/$1.env" 2>/dev/null | sed -n "s/^$2=//p" | tail -n 1 | tr -d "'\""
|
||
}
|
||
|
||
# CSQTT: the rule PROCESS-NAME,csqtt,DIRECT keeps the client's own connections
|
||
# (VK, TURN, server) out of its tunnel; nikki's mixin sets find-process-mode from
|
||
# match_process (default off), and with off the rule never matches -> a loop
|
||
csqtt_match_process() {
|
||
[ "$(profile_val "$1" CSQTT)" = 1 ] || return 0
|
||
case "$(uci -q get nikki.mixin.match_process)" in
|
||
strict | always) ;;
|
||
*) uci set nikki.mixin.match_process=strict && log "nikki: match_process=strict (CSQTT needs PROCESS-NAME)" ;;
|
||
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=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.
|
||
LITE_MEM_DEFAULT=64MiB
|
||
|
||
# GOMEMLIMIT (soft limit of the Go heap, the main lever for mihomo's RSS) as a line
|
||
# with a marker after the anchor of patch_init: replaced or removed on every use /
|
||
# fix, and put back by fix after a nikki upgrade. Comes after nikki's own
|
||
# GOMEMLIMIT (procd env_go_mem_limit), so the kit's value wins.
|
||
mem_env() {
|
||
f=/etc/init.d/nikki
|
||
[ -f "$f" ] || return 0
|
||
_n=${1:-$(uci -q get nikki.config.profile)}
|
||
_n=${_n#file:}
|
||
_n=${_n%.yaml}
|
||
_lim=""
|
||
if [ "$(profile_val "$_n" LITE)" = 1 ]; then
|
||
_lim=$(profile_val "$_n" LITE_GOMEMLIMIT)
|
||
: "${_lim:=$LITE_MEM_DEFAULT}"
|
||
# digits + B / KiB / MiB / GiB (also goes into sed and the init script)
|
||
case "$_lim" in [1-9]*) _u=${_lim#"${_lim%%[!0-9]*}"} ;; *) _u=bad ;; esac
|
||
case "$_u" in
|
||
'' | B | KiB | MiB | GiB) ;;
|
||
*)
|
||
log "warning: LITE_GOMEMLIMIT=$_lim is not like 64MiB, using $LITE_MEM_DEFAULT"
|
||
_lim=$LITE_MEM_DEFAULT
|
||
;;
|
||
esac
|
||
fi
|
||
_line=" procd_append_param env GOMEMLIMIT=$_lim # mihomo-kit lite"
|
||
grep -qxF "$_line" "$f" && [ -n "$_lim" ] && return 0
|
||
sed -i '/# mihomo-kit lite$/d' "$f"
|
||
[ -n "$_lim" ] || return 0
|
||
_anchor="procd_append_param env SKIP_SYSTEM_IPV6_CHECK"
|
||
if ! grep -q "$_anchor" "$f"; then
|
||
log "warning: LITE: anchor not found in $f, GOMEMLIMIT not set (nikki LuCI: GOMEMLIMIT=$_lim)"
|
||
return 0
|
||
fi
|
||
sed -i "/$_anchor/a\\$_line" "$f"
|
||
log "nikki: GOMEMLIMIT=$_lim"
|
||
}
|
||
|
||
# nikki's mixin wins over the profile: quiet log, no process lookup (CSQTT keeps strict)
|
||
lite_uci() {
|
||
[ "$(profile_val "$1" LITE)" = 1 ] || return 0
|
||
case "$(uci -q get nikki.mixin.log_level)" in
|
||
info | debug) uci set nikki.mixin.log_level=warning && log "nikki: log_level=warning (LITE)" ;;
|
||
esac
|
||
[ "$(profile_val "$1" LITE_TPROXY)" = 0 ] || lite_intercept
|
||
[ "$(profile_val "$1" CSQTT)" = 1 ] && return 0
|
||
case "$(uci -q get nikki.mixin.match_process)" in
|
||
strict | always) uci set nikki.mixin.match_process=off && log "nikki: match_process=off (LITE)" ;;
|
||
esac
|
||
}
|
||
|
||
# interception without TUN (its device and, for UDP, the gvisor stack cost memory):
|
||
# TCP by redirect, UDP by tproxy (kmod-nft-tproxy, installed if missing), TUN off.
|
||
# Modes that are already redirect / tproxy stay. LITE_TPROXY=0 leaves all of it to you.
|
||
lite_intercept() {
|
||
_tcp=$(uci -q get nikki.proxy.tcp_mode) _udp=$(uci -q get nikki.proxy.udp_mode)
|
||
if [ "$_udp" = tun ]; then
|
||
if [ ! -d /sys/module/nft_tproxy ] && ! opkg list-installed 2>/dev/null | grep -q '^kmod-nft-tproxy '; then
|
||
log "LITE: installing kmod-nft-tproxy"
|
||
{ opkg update && opkg install kmod-nft-tproxy; } >/dev/null 2>&1 || {
|
||
log "warning: LITE: kmod-nft-tproxy not installed (opkg), interception left as is"
|
||
return 0
|
||
}
|
||
fi
|
||
fi
|
||
[ "$_tcp" = tun ] && uci set nikki.proxy.tcp_mode=redirect && log "nikki: tcp_mode=redirect (LITE)"
|
||
[ "$_udp" = tun ] && uci set nikki.proxy.udp_mode=tproxy && log "nikki: udp_mode=tproxy (LITE)"
|
||
[ "$(uci -q get nikki.mixin.tun_enabled)" = 1 ] && uci set nikki.mixin.tun_enabled=0 && log "nikki: tun_enabled=0 (LITE)"
|
||
return 0
|
||
}
|
||
|
||
# after the restart: is GOMEMLIMIT in the core, and what else costs memory
|
||
lite_check() {
|
||
[ "$(profile_val "$1" LITE)" = 1 ] || return 0
|
||
_pid="" _w=0
|
||
while [ -z "$_pid" ] && [ "$_w" -lt 10 ]; do
|
||
_pid=$(pidof mihomo)
|
||
[ -n "$_pid" ] || { sleep 1; _w=$((_w + 1)); }
|
||
done
|
||
if [ -z "$_pid" ]; then
|
||
log "warning: LITE: mihomo is not running"
|
||
elif ! tr '\0' '\n' < "/proc/${_pid%% *}/environ" 2>/dev/null | grep -q '^GOMEMLIMIT=.'; then
|
||
log "warning: LITE: no GOMEMLIMIT in the running core (run: mihomo-kit.sh fix)"
|
||
fi
|
||
if [ "$(uci -q get nikki.proxy.tcp_mode)" != tun ] && [ "$(uci -q get nikki.proxy.udp_mode)" != tun ] &&
|
||
[ "$(uci -q get nikki.mixin.tun_enabled)" = 1 ]; then
|
||
# traffic goes by redirect/tproxy, the TUN device is up for nothing
|
||
log "warning: LITE: TUN is on but nikki sends nothing into it; to save memory:" \
|
||
"uci set nikki.mixin.tun_enabled=0; uci commit nikki; /etc/init.d/nikki restart"
|
||
elif [ "$(uci -q get nikki.proxy.tcp_mode)" = tun ] || [ "$(uci -q get nikki.proxy.udp_mode)" = tun ]; then
|
||
log "warning: LITE: nikki uses TUN (stack $(uci -q get nikki.mixin.tun_stack)); without it less memory:" \
|
||
"opkg install kmod-nft-tproxy; uci set nikki.proxy.tcp_mode=redirect; uci set nikki.proxy.udp_mode=tproxy;" \
|
||
"uci set nikki.mixin.tun_enabled=0; uci commit nikki; /etc/init.d/nikki restart" \
|
||
"(or at least nikki.mixin.tun_stack=system)"
|
||
fi
|
||
[ "$(profile_val "$1" TAILSCALE)" = 1 ] &&
|
||
log "warning: LITE: the embedded Tailscale (tsnet with its own network stack) takes tens of MB; turn it off if not needed"
|
||
[ "$(profile_val "$1" CSQTT)" = 1 ] &&
|
||
log "warning: LITE: CSQTT needs process lookup (match_process=strict): every connection scans /proc"
|
||
return 0
|
||
}
|
||
|
||
# A new router (no settings yet): interception without TUN, as LITE does (TCP
|
||
# redirect, UDP tproxy), and no IPv6 anywhere in nikki. Once the settings are
|
||
# saved, nikki's own settings are left to the user.
|
||
nikki_defaults() {
|
||
[ -f "$PROFILES_D/common.env" ] && return 0
|
||
uci -q get nikki.proxy > /dev/null || return 0
|
||
lite_intercept
|
||
for _o in mixin.ipv6 mixin.dns_ipv6 proxy.ipv6_dns_hijack proxy.ipv6_proxy; do
|
||
[ "$(uci -q get "nikki.$_o")" = 0 ] || { uci set "nikki.$_o=0" && log "nikki: $_o=0"; }
|
||
done
|
||
uci commit nikki
|
||
}
|
||
|
||
cmd_use() {
|
||
[ $# -eq 1 ] || die "usage: use <name>"
|
||
[ -f "$PROFILES_OUT/$1.yaml" ] || die "no $PROFILES_OUT/$1.yaml, run build first"
|
||
uci set nikki.config.profile="file:$1.yaml"
|
||
# a profile to run: nikki on, also after a reboot
|
||
[ "$(uci -q get nikki.config.enabled)" = 1 ] || { uci set nikki.config.enabled=1 && log "nikki: enabled"; }
|
||
/etc/init.d/nikki enabled || /etc/init.d/nikki enable
|
||
lite_uci "$1"
|
||
csqtt_match_process "$1"
|
||
ipv6_proxy_off
|
||
uci commit nikki
|
||
mem_env "$1"
|
||
/etc/init.d/nikki restart
|
||
log "nikki now runs $1"
|
||
lite_check "$1"
|
||
# OpenVPN of this profile
|
||
[ "$(profile_val "$1" OPENVPN)" = 1 ] && command -v ovpn.sh >/dev/null 2>&1 || return 0
|
||
# off now (manual, schedule): up says so and does nothing
|
||
ovpn.sh want || {
|
||
ovpn.sh up
|
||
return 0
|
||
}
|
||
# the init script wrote a fresh OTP and the kit core is already connecting: refresh
|
||
# only if the tunnel does not answer; if it does not come up, cron
|
||
# (ovpn.sh check) retries
|
||
sleep 5
|
||
ovpn.sh up || log "warning: OpenVPN did not come up yet, the cron check retries within a minute"
|
||
return 0
|
||
}
|
||
|
||
# --- CSQTT on/off ------------------------------------------------------------
|
||
# The csqtt service (star-panel-csqtt) and the group UPLINK, always in this order,
|
||
# so the nodes never dial through a missing csqtt0:
|
||
# on main.enabled=1 + start, wait until connected (csqtt status = 0), UPLINK=CSQTT
|
||
# off UPLINK=DIRECT, then stop + main.enabled=0 (stays off on boot / WAN up)
|
||
# state key=value lines for LuCI (no traffic through the tunnel)
|
||
CSQTT_WAIT=${CSQTT_WAIT:-90}
|
||
|
||
uplink_now() { api_get /proxies/UPLINK 2>/dev/null | jsonfilter -e '@.now' 2>/dev/null; }
|
||
uplink_set() {
|
||
api_get /proxies/UPLINK -X PUT -H 'Content-Type: application/json' -d "{\"name\":\"$1\"}" >/dev/null 2>&1
|
||
}
|
||
|
||
# csqtt status (exit 0 connected, 1 not, 2 service not running) -> _cq_rc, _cq_out
|
||
csqtt_status() {
|
||
_cq_out=$(csqtt status 2>/dev/null)
|
||
_cq_rc=$?
|
||
}
|
||
|
||
# single-quoted, without characters that break eval in rpcd
|
||
cq_quote() { printf "'%s'" "$(printf '%s' "$1" | tr -d "'\"\`\\\\\$\n" | cut -c1-200)"; }
|
||
|
||
cmd_csqtt() {
|
||
command -v csqtt >/dev/null 2>&1 || die "csqtt is not installed (star-panel-csqtt)"
|
||
case "${1:-}" in
|
||
on)
|
||
[ -n "$(uplink_now)" ] || die "no group UPLINK in the running profile: tick CSQTT in the settings (CSQTT=1), save and apply"
|
||
uci set csqtt.main.enabled=1
|
||
uci commit csqtt
|
||
/etc/init.d/csqtt start
|
||
log "csqtt: waiting for the tunnel, up to $CSQTT_WAIT s"
|
||
_w=0
|
||
while csqtt_status; [ "$_cq_rc" != 0 ]; do
|
||
if [ "$_w" -ge "$CSQTT_WAIT" ]; then
|
||
printf '%s\n' "$_cq_out" | grep -E '^(connectivity|last error|captcha):' >&2
|
||
die "csqtt did not connect in $CSQTT_WAIT s; UPLINK stays $(uplink_now), the service keeps trying (press again later)"
|
||
fi
|
||
sleep 3
|
||
_w=$((_w + 3))
|
||
done
|
||
uplink_set CSQTT || die "csqtt is up, but UPLINK=CSQTT failed (mihomo API)"
|
||
log "csqtt connected, UPLINK=CSQTT: the nodes now connect through ${CSQTT_IFACE:-csqtt0}"
|
||
;;
|
||
off)
|
||
if [ -n "$(uplink_now)" ]; then
|
||
uplink_set DIRECT && log "UPLINK=DIRECT" || log "warning: UPLINK=DIRECT failed (mihomo API)"
|
||
fi
|
||
uci set csqtt.main.enabled=0
|
||
uci commit csqtt
|
||
/etc/init.d/csqtt stop
|
||
log "csqtt stopped (main.enabled=0: it stays off until csqtt on)"
|
||
;;
|
||
state)
|
||
csqtt_status
|
||
case "$_cq_rc" in 0) _l=up ;; 2) _l=stopped ;; *) _l=connecting ;; esac
|
||
echo "link=$_l"
|
||
echo "enabled=$(uci -q get csqtt.main.enabled || echo 0)"
|
||
echo "uplink=$(uplink_now)"
|
||
echo "active=$(printf '%s\n' "$_cq_out" | sed -n 's/^selection:.*active: *\([A-Za-z0-9_.-]*\).*/\1/p')"
|
||
echo "stage=$(printf '%s\n' "$_cq_out" | sed -n 's/^connectivity: *stage=\([A-Za-z0-9_-]*\).*/\1/p')"
|
||
echo "captcha=$(printf '%s\n' "$_cq_out" | sed -n 's/^captcha: *\([0-9]*\) pending.*/\1/p')"
|
||
echo "stats=$(cq_quote "$(printf '%s\n' "$_cq_out" | sed -n 's/^stats: *//p')")"
|
||
_e=$(printf '%s\n' "$_cq_out" | sed -n 's/^last error: *//p')
|
||
[ "$_e" = none ] && _e=
|
||
echo "err=$(cq_quote "$_e")"
|
||
;;
|
||
*) die "usage: csqtt on|off|state" ;;
|
||
esac
|
||
}
|
||
|
||
# --- Tailscale login --------------------------------------------------------
|
||
|
||
TS_DIR="$NIKKI_DIR/run/tailscale"
|
||
CORE_LOG=/var/log/nikki/core.log
|
||
|
||
# mihomo API from nikki's mixin settings (same as ovpn.sh)
|
||
api_get() {
|
||
l=$(uci -q get nikki.mixin.api_listen)
|
||
port=${l##*:} host=${l%:*}
|
||
case "$port" in '' | *[!0-9]*) port=9090 ;; esac
|
||
case "$host" in '' | 0.0.0.0 | '[::]' | '::' | '*' | "$l") host=127.0.0.1 ;; esac
|
||
sec=$(uci -q get nikki.mixin.api_secret)
|
||
path=$1
|
||
shift
|
||
curl -fsS -m 15 ${sec:+-H "Authorization: Bearer $sec"} "$@" "http://$host:$port$path"
|
||
}
|
||
|
||
ts_logged_in() {
|
||
grep -q '_current-profile' "$TS_DIR/tailscaled.state" 2>/dev/null
|
||
}
|
||
|
||
# The node starts on first use and prints the login URL once, at info level.
|
||
# A failed first start leaves a half-made state that stays silent, so start
|
||
# from an empty state dir with the log at info.
|
||
cmd_ts_login() {
|
||
if [ "${1:-}" != -f ] && ts_logged_in; then
|
||
log "Tailscale node is already logged in (ts-login -f to start over)"
|
||
return 0
|
||
fi
|
||
lvl=$(uci -q get nikki.mixin.log_level)
|
||
case "$lvl" in info | debug) ;; *) uci set nikki.mixin.log_level=info; uci commit nikki ;; esac
|
||
/etc/init.d/nikki stop
|
||
rm -rf "${TS_DIR:?}"
|
||
skip=$(wc -l < "$CORE_LOG" 2>/dev/null || echo 0)
|
||
/etc/init.d/nikki start
|
||
url=
|
||
i=0
|
||
while [ $i -lt 12 ]; do
|
||
i=$((i + 1))
|
||
# nikki may truncate the log on start
|
||
[ "$(wc -l < "$CORE_LOG" 2>/dev/null || echo 0)" -lt "$skip" ] && skip=0
|
||
url=$(tail -n "+$((skip + 1))" "$CORE_LOG" 2>/dev/null |
|
||
sed -n 's/.*To start this tsnet server.* go to: \(https:[^ "]*\).*/\1/p' | tail -n 1)
|
||
[ -n "$url" ] && break
|
||
# any dial through the node starts it
|
||
api_get /proxies/TAILSCALE/delay -G --data-urlencode "url=http://100.100.100.100/" \
|
||
--data-urlencode timeout=5000 >/dev/null 2>&1 || sleep 5
|
||
done
|
||
if [ "$lvl" != "$(uci -q get nikki.mixin.log_level)" ]; then
|
||
uci set nikki.mixin.log_level="${lvl:-warning}"
|
||
uci commit nikki
|
||
fi
|
||
if [ -z "$url" ]; then
|
||
log "no login URL in $CORE_LOG; check: grep '\[Tailscale\]' $CORE_LOG"
|
||
case "$(uci -q get nikki.config.profile)" in
|
||
*whitelist*) log "on whitelist Tailscale reaches its control server through MY; log in from the main (or foreign) profile, then switch back" ;;
|
||
esac
|
||
return 1
|
||
fi
|
||
{
|
||
echo "Tailscale: войди по ссылке, потом в админке Tailscale — Disable key expiry для ноды"
|
||
echo " $url"
|
||
} >&2
|
||
}
|
||
|
||
# --- router setup -----------------------------------------------------------
|
||
|
||
# unpacked core size to expect, for the free space check (KiB)
|
||
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?
|
||
core_ok() {
|
||
if [ "$MIHOMO_VERSION" = stock ]; then
|
||
[ "$(readlink /usr/bin/mihomo)" = "$STOCK_CORE" ]
|
||
else
|
||
[ "$(mihomo -v 2>/dev/null | awk '{print $3; exit}')" = "$MIHOMO_VERSION" ]
|
||
fi
|
||
}
|
||
|
||
# download URL of the wanted core for this router's arch; non-zero for an unknown arch
|
||
core_url() {
|
||
case "$(uname -m)" in
|
||
aarch64) _arch=arm64 ;;
|
||
x86_64) _arch=amd64 ;;
|
||
armv7l) _arch=armv7 ;;
|
||
mips) _arch=mips-softfloat ;;
|
||
mipsel | mipsle) _arch=mipsle-softfloat ;;
|
||
*) return 1 ;;
|
||
esac
|
||
echo "$MIHOMO_BASE/mihomo-linux-$_arch-$MIHOMO_VERSION.gz"
|
||
}
|
||
|
||
# can the wanted core be installed now: the package core is there, or the
|
||
# download answers (first byte only)
|
||
core_available() {
|
||
if [ "$MIHOMO_VERSION" = stock ]; then
|
||
[ -x "$STOCK_CORE" ]
|
||
return
|
||
fi
|
||
_url=$(core_url) && curl -fsL -r 0-0 -m 30 -o /dev/null "$_url"
|
||
}
|
||
|
||
# Core change in two steps around the nikki restart (cmd_fix): core_fetch while
|
||
# nikki still runs - the router may reach the download host only through mihomo -
|
||
# then core_install with nikki stopped. CORE_PENDING: "" (nothing), stock or new.
|
||
core_fetch() {
|
||
CORE_PENDING=""
|
||
cur=$(mihomo -v 2>/dev/null | awk '{print $3; exit}')
|
||
if core_ok; then
|
||
log "mihomo core is $cur"
|
||
return 0
|
||
fi
|
||
if [ "$MIHOMO_VERSION" = stock ]; then
|
||
if [ ! -x "$STOCK_CORE" ]; then
|
||
log "warning: no package core at $STOCK_CORE, keeping $cur"
|
||
return 1
|
||
fi
|
||
CORE_PENDING=stock
|
||
return 0
|
||
fi
|
||
url=$(core_url) || {
|
||
log "warning: unknown arch $(uname -m), set the core manually"
|
||
return 1
|
||
}
|
||
log "updating mihomo core ${cur:-none} -> $MIHOMO_VERSION"
|
||
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
|
||
_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" ||
|
||
[ "$("$new" -v 2>/dev/null | awk '{print $3; exit}')" != "$MIHOMO_VERSION" ]; then
|
||
rm -f "$new"
|
||
log "warning: core $MIHOMO_VERSION not installed (download, unpack or check failed: $url;" \
|
||
"free space in ${new%/*}: $(df -h "${new%/*}" 2>/dev/null | awk 'NR==2 {print $4}')), keeping ${cur:-the current one}"
|
||
return 1
|
||
fi
|
||
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() {
|
||
case "${CORE_PENDING:-}" in
|
||
stock)
|
||
# back to the package's core: /usr/bin/mihomo becomes a symlink to it again
|
||
rm -f /usr/bin/mihomo /usr/bin/mihomo.new /usr/bin/mihomo.bak
|
||
ln -s "$STOCK_CORE" /usr/bin/mihomo
|
||
log "core: the package's $("$STOCK_CORE" -v 2>/dev/null | awk '{print $3; exit}')"
|
||
;;
|
||
new)
|
||
if [ "$CORE_NEW" = "$bin.new" ]; then
|
||
mv "$bin.new" "$bin"
|
||
else
|
||
core_swap || { CORE_PENDING=""; return 1; }
|
||
fi
|
||
log "core: $(mihomo -v | head -n 1)"
|
||
;;
|
||
esac
|
||
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.
|
||
# 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).
|
||
patch_init() {
|
||
f=/etc/init.d/nikki
|
||
_anchor="procd_append_param env SKIP_SYSTEM_IPV6_CHECK"
|
||
if ! grep -q "$_anchor" "$f"; then
|
||
log "warning: anchor not found in $f, add 'procd_append_param env TS_FORCE_NOISE_443=true' and '/usr/bin/ovpn.sh write' by hand"
|
||
return 0
|
||
fi
|
||
if grep -q TS_FORCE_NOISE_443 "$f"; then
|
||
log "init script already has TS_FORCE_NOISE_443"
|
||
else
|
||
sed -i "/$_anchor/a\\ procd_append_param env TS_FORCE_NOISE_443=true" "$f"
|
||
log "added TS_FORCE_NOISE_443 to $f"
|
||
fi
|
||
# the line of kits before 2026-11 named the script bmstu-otp.sh
|
||
grep -q "bmstu-otp.sh write" "$f" && sed -i 's|bmstu-otp\.sh|ovpn.sh|g' "$f"
|
||
if grep -q "ovpn.sh write" "$f"; then
|
||
log "init script already writes the OpenVPN provider"
|
||
else
|
||
sed -i "/$_anchor/a\\ [ -x /usr/bin/ovpn.sh ] \\&\\& /usr/bin/ovpn.sh write >/dev/null 2>\\&1" "$f"
|
||
log "added ovpn.sh write to $f"
|
||
fi
|
||
mem_env
|
||
}
|
||
|
||
# nikki skips these ranges before mihomo; Tailscale (100.64/10) and the
|
||
# OpenVPN internal nets (172.16/12) must reach mihomo rules.
|
||
fix_reserved() {
|
||
for net in 100.64.0.0/10 172.16.0.0/12; do
|
||
uci -q del_list nikki.proxy.reserved_ip="$net" && log "removed $net from nikki reserved_ip"
|
||
done
|
||
uci commit nikki
|
||
}
|
||
|
||
# Wired WAN first: wan/wan6 metric 10, other uplinks (modems, wifi client)
|
||
# 50, 60, ... in uci order. Interfaces with a metric already set are left alone.
|
||
wan_metrics() {
|
||
_changed=0 _m=50
|
||
for _if in $(uci -q show network | sed -n 's/^network\.\([^.=]*\)=interface$/\1/p'); do
|
||
case "$_if" in lan | loopback) continue ;; esac
|
||
case "$(uci -q get "network.$_if.proto")" in
|
||
dhcp | dhcpv6 | pppoe | qmi | mbim | ncm | 3g | modemmanager | qcm | wwan) ;;
|
||
*) continue ;;
|
||
esac
|
||
case "$_if" in
|
||
wan | wan6) _want=10 ;;
|
||
*) _want=$_m _m=$((_m + 10)) ;;
|
||
esac
|
||
[ -n "$(uci -q get "network.$_if.metric")" ] && continue
|
||
uci set "network.$_if.metric=$_want"
|
||
log "network.$_if.metric=$_want"
|
||
_changed=1
|
||
done
|
||
[ "$_changed" = 1 ] || return 0
|
||
uci commit network
|
||
/etc/init.d/network reload
|
||
}
|
||
|
||
# dnsmasq rebind protection drops answers in 100.64.0.0/10, i.e. the tailnet
|
||
# addresses MagicDNS returns for *.ts.net; exempt the domain.
|
||
dns_rebind_exempt() {
|
||
uci -q get dhcp.@dnsmasq[0] > /dev/null || return 0
|
||
uci -q get dhcp.@dnsmasq[0].rebind_domain | grep -qw 'ts.net' && return 0
|
||
uci add_list dhcp.@dnsmasq[0].rebind_domain='ts.net'
|
||
uci commit dhcp
|
||
/etc/init.d/dnsmasq restart
|
||
log "dnsmasq: rebind_domain ts.net"
|
||
}
|
||
|
||
# profiles home/street were renamed to main/whitelist: move the env files and
|
||
# the profile nikki runs (the old yaml goes away with the next build)
|
||
migrate_profiles() {
|
||
for _pair in home:main street:whitelist; do
|
||
_old=${_pair%%:*} _new=${_pair#*:}
|
||
[ -f "$PROFILES_D/$_old.env" ] && [ ! -f "$PROFILES_D/$_new.env" ] || continue
|
||
sed "s/^LOCATION=$_old\$/LOCATION=$_new/" "$PROFILES_D/$_old.env" > "$PROFILES_D/$_new.env"
|
||
chmod 600 "$PROFILES_D/$_new.env"
|
||
rm -f "$PROFILES_D/$_old.env"
|
||
if [ "$(uci -q get nikki.config.profile)" = "file:$_old.yaml" ]; then
|
||
uci set nikki.config.profile="file:$_new.yaml"
|
||
uci commit nikki
|
||
fi
|
||
log "profile $_old renamed to $_new"
|
||
done
|
||
}
|
||
|
||
# Kits before 2026-11 had OpenVPN for one server (BMSTU): its files were bmstu.*,
|
||
# and its addresses were the defaults. The files move to openvpn.*, the addresses
|
||
# go into common.env, cron and the init script call ovpn.sh.
|
||
# ovpn_old_defaults <common.env>: what that server had by default, unless set
|
||
ovpn_old_defaults() {
|
||
[ -f "$1" ] || return 0
|
||
grep -q '^OVPN_ROUTES=' "$1" || echo "OVPN_ROUTES='172.16.0.0/16 172.19.33.0/24 195.19.32.0/19'" >> "$1"
|
||
grep -q '^OVPN_SERVER_IPS=' "$1" || echo "OVPN_SERVER_IPS='195.19.40.7 195.19.33.86'" >> "$1"
|
||
grep -q '^OVPN_CHECK_URL=' "$1" || echo "OVPN_CHECK_URL='https://eu.bmstu.ru'" >> "$1"
|
||
log "OpenVPN: the networks and addresses of the old defaults kept in $1"
|
||
}
|
||
|
||
migrate_openvpn() {
|
||
_moved=0
|
||
for _x in env ovpn off until; do
|
||
_o=$NIKKI_DIR/bmstu.$_x _n=$NIKKI_DIR/openvpn.$_x
|
||
[ -f "$_o" ] || continue
|
||
if [ -f "$_n" ]; then
|
||
rm -f "$_o"
|
||
else
|
||
mv "$_o" "$_n"
|
||
log "moved $_o to $_n"
|
||
[ "$_x" = ovpn ] && _moved=1
|
||
fi
|
||
done
|
||
rm -f "$NIKKI_DIR"/run/providers/bmstu.yaml "$NIKKI_DIR"/run/providers/bmstu-routes.*
|
||
[ "$_moved" = 1 ] && ovpn_old_defaults "$PROFILES_D/common.env"
|
||
if grep -q 'bmstu-otp.sh check' /etc/crontabs/root 2>/dev/null; then
|
||
sed -i 's|bmstu-otp\.sh check|ovpn.sh check|' /etc/crontabs/root
|
||
/etc/init.d/cron restart
|
||
log "cron: ovpn.sh check"
|
||
fi
|
||
}
|
||
|
||
install_files() {
|
||
for s in mihomo-kit.sh ovpn.sh; do
|
||
chmod +x "$KIT_DIR/router/$s"
|
||
ln -sf "$KIT_DIR/router/$s" "/usr/bin/$s"
|
||
done
|
||
# the old name, for scripts and habits
|
||
ln -sf "$KIT_DIR/router/ovpn.sh" /usr/bin/bmstu-otp.sh
|
||
mkdir -p "$PROFILES_D"
|
||
chmod 700 "$PROFILES_D"
|
||
migrate_profiles
|
||
migrate_openvpn
|
||
# new presets (e.g. foreign) for routers that are already set up
|
||
if [ -f "$PROFILES_D/common.env" ]; then
|
||
for f in "$KIT_DIR"/presets/*.env; do
|
||
[ -f "$PROFILES_D/${f##*/}" ] || { cp "$f" "$PROFILES_D/" && chmod 600 "$PROFILES_D/${f##*/}"; }
|
||
done
|
||
fi
|
||
install_luci
|
||
}
|
||
|
||
# LuCI pages "Services -> mihomo-kit" (luci/): rpcd plugin, ACL, menu, views.
|
||
# A view goes to view/mihomo-kit/<v|g><hash>.js and the menu points there: LuCI
|
||
# loads views by script with a ?v= of its own version, which neither a kit
|
||
# update nor a hard reload changes, so a fixed name stays cached in the browser.
|
||
install_luci() {
|
||
src=$KIT_DIR/luci
|
||
[ -d "$src" ] && [ -d /www/luci-static/resources ] || return 0
|
||
_changed=0 _rpcd=0
|
||
# put <src> <dst> <mode>; uhttpd answers 403 for files that are not world-readable,
|
||
# and a run from LuCI inherits rpcd's umask 077
|
||
put() {
|
||
if ! cmp -s "$1" "$2"; then
|
||
mkdir -p "$(dirname "$2")"
|
||
cp "$1" "$2"
|
||
_changed=1
|
||
fi
|
||
chmod "$3" "$2"
|
||
}
|
||
put "$src/rpcd.sh" /usr/libexec/rpcd/mihomo-kit 755
|
||
put "$src/acl.json" /usr/share/rpcd/acl.d/luci-app-mihomo-kit.json 644
|
||
# rpcd needs a restart only for its plugin and ACL (it drops LuCI sessions)
|
||
_rpcd=$_changed
|
||
put "$src/qrcode.js" /www/luci-static/resources/mihomo-kit/qrcode.js 644
|
||
put "$src/servers.js" /www/luci-static/resources/mihomo-kit/servers.js 644
|
||
put "$src/graph.js" /www/luci-static/resources/mihomo-kit/graph.js 644
|
||
|
||
# pages: "Управление" (mihomo-kit.js -> v<hash>.js) and "Граф" (mihomo-kit-graph.js -> g<hash>.js)
|
||
_views=/www/luci-static/resources/view
|
||
# Dependencies matter too: a changed graph.js must invalidate both the view URL
|
||
# and its script URL, including a global left by navigation inside LuCI.
|
||
_assets=$(cat "$src/graph.js" "$src/servers.js" "$src/qrcode.js" | md5sum | cut -c1-8)
|
||
_v=v$(cat "$src/mihomo-kit.js" "$src/graph.js" "$src/servers.js" "$src/qrcode.js" | md5sum | cut -c1-8)
|
||
_g=g$(cat "$src/mihomo-kit-graph.js" "$src/graph.js" "$src/servers.js" "$src/qrcode.js" | md5sum | cut -c1-8)
|
||
_viewtmp=/tmp/mihomo-kit-view-$$.js
|
||
sed "s/__MIHOMO_KIT_ASSETS__/$_assets/g" "$src/mihomo-kit.js" > "$_viewtmp"
|
||
put "$_viewtmp" "$_views/mihomo-kit/$_v.js" 644
|
||
sed "s/__MIHOMO_KIT_ASSETS__/$_assets/g" "$src/mihomo-kit-graph.js" > "$_viewtmp"
|
||
put "$_viewtmp" "$_views/mihomo-kit/$_g.js" 644
|
||
rm -f "$_viewtmp"
|
||
for _f in "$_views/mihomo-kit.js" "$_views"/mihomo-kit/*.js; do
|
||
case "$_f" in "$_views/mihomo-kit/$_v.js" | "$_views/mihomo-kit/$_g.js") continue ;; esac
|
||
[ -f "$_f" ] && rm -f "$_f" && _changed=1
|
||
done
|
||
sed -e "s|\"path\": \"mihomo-kit\"|\"path\": \"mihomo-kit/$_v\"|" \
|
||
-e "s|\"path\": \"mihomo-kit-graph\"|\"path\": \"mihomo-kit/$_g\"|" "$src/menu.json" > /tmp/mihomo-kit-menu.json
|
||
put /tmp/mihomo-kit-menu.json /usr/share/luci/menu.d/luci-app-mihomo-kit.json 644
|
||
rm -f /tmp/mihomo-kit-menu.json
|
||
|
||
[ "$_changed" = 1 ] || return 0
|
||
rm -rf /tmp/luci-indexcache* /tmp/luci-modulecache
|
||
log "LuCI page installed: Services -> mihomo-kit"
|
||
[ "$_rpcd" = 1 ] || return 0
|
||
# rpcd loads plugins and ACLs only on start. Not "rpcd restart": run from a job LuCI
|
||
# started (kit update) this shell is rpcd's descendant, and the stop can take it down
|
||
# before the start - rpcd stays dead, LuCI says "Object not found" and rejects the
|
||
# password until a reboot. SIGHUP (through procd: to rpcd itself, not its plugins)
|
||
# makes rpcd re-exec in place and keep the LuCI sessions; then make sure it runs.
|
||
# Delayed so the job gets to finish first.
|
||
(
|
||
sleep 5
|
||
ubus call service signal '{"name":"rpcd","signal":1}' || kill -HUP "$(pidof rpcd | cut -d' ' -f1)"
|
||
sleep 5
|
||
pidof rpcd || /etc/init.d/rpcd start
|
||
) < /dev/null > /dev/null 2>&1 &
|
||
}
|
||
|
||
enable_otp_cron() {
|
||
grep -q "ovpn.sh check" /etc/crontabs/root 2>/dev/null && return 0
|
||
echo '* * * * * /usr/bin/ovpn.sh check' >> /etc/crontabs/root
|
||
/etc/init.d/cron restart
|
||
log "added ovpn.sh check to cron"
|
||
}
|
||
|
||
# opkg_fit <package>...: install from the feeds on a small flash. opkg checks every
|
||
# package's Installed-Size (unpacked) against the free space, but a compressing
|
||
# overlay (ubifs, jffs2) stores the files at about their .ipk size: mihomo is ~55 MB
|
||
# unpacked and ~20 MB as .ipk, so opkg refuses what fits. Here the packages opkg
|
||
# would install are counted by .ipk size there (Installed-Size on other file systems)
|
||
# + PKG_RESERVE_KB, then --force-space. The .ipk files are downloaded to /tmp (RAM).
|
||
opkg_fit() {
|
||
_new=$(opkg --noaction --force-space install "$@" 2>/dev/null | sed -n 's/^Installing \([^ ]*\) (.*/\1/p')
|
||
if [ -z "$_new" ]; then
|
||
opkg install "$@"
|
||
return
|
||
fi
|
||
_field=Installed-Size
|
||
case "$(awk '$2 == "/overlay" {print $3; exit}' /proc/mounts)" in ubifs | jffs2) _field=Size ;; esac
|
||
_need=0
|
||
for _p in $_new; do
|
||
_b=$(opkg info "$_p" | sed -n "s/^$_field: *//p" | head -n 1)
|
||
case "$_b" in '' | *[!0-9]*) _b=0 ;; esac
|
||
_need=$((_need + (_b + 1023) / 1024))
|
||
done
|
||
_free=$(df -k / 2>/dev/null | awk 'NR==2 {print $4}')
|
||
_new=$(echo $_new)
|
||
log "packages $_new: about $_need KB on flash ($_field), free ${_free:-?} KB"
|
||
[ $((${_free:-0} - _need)) -ge "$PKG_RESERVE_KB" ] ||
|
||
die "not enough flash for $_new: free $((PKG_RESERVE_KB + _need - ${_free:-0})) KB more"
|
||
opkg install --force-space "$@"
|
||
}
|
||
|
||
# --- nikki from its release bundle ------------------------------------------
|
||
# A release of OpenWrt-nikki has one nikki_<arch>-<branch>.tar.gz per router type, and
|
||
# each is a whole opkg feed: Packages(.gz) signed with nikki's key + the .ipk files.
|
||
# nikki_feed unpacks the one for this router into RAM and adds it as a temporary feed,
|
||
# so opkg checks the signature (key from the kit: router/nikki-key-build.pub), takes
|
||
# the dependencies from the OpenWrt feeds and opkg_fit counts the flash as usual.
|
||
# The bundle comes from NIKKI_BASES (the kit's mirror first, then GitHub), or from
|
||
# the file NIKKI_TGZ copied to the router by hand.
|
||
NIKKI_FEED=/tmp/nikki-feed
|
||
NIKKI_FEED_CONF=/etc/opkg/nikki-kit.conf
|
||
|
||
# nikki_bundle: the bundle name for this router (after . /etc/openwrt_release)
|
||
nikki_bundle() {
|
||
case "${DISTRIB_RELEASE:-}" in
|
||
*24.10*) echo "nikki_${DISTRIB_ARCH:-?}-openwrt-24.10.tar.gz" ;;
|
||
*) return 1 ;;
|
||
esac
|
||
}
|
||
|
||
nikki_feed_drop() {
|
||
rm -rf "$NIKKI_FEED" "$NIKKI_FEED_CONF" /var/opkg-lists/nikki_kit
|
||
}
|
||
|
||
nikki_feed() {
|
||
[ -f /etc/openwrt_release ] && . /etc/openwrt_release
|
||
_bundle=$(nikki_bundle) ||
|
||
die "nikki: OpenWrt ${DISTRIB_RELEASE:-?} не поддерживается (нужна 24.10 с opkg)"
|
||
nikki_feed_drop
|
||
mkdir -p "$NIKKI_FEED"
|
||
if [ -n "${NIKKI_TGZ:-}" ]; then
|
||
log "nikki: unpacking $NIKKI_TGZ"
|
||
tar xzf "$NIKKI_TGZ" -C "$NIKKI_FEED" || die "nikki: $NIKKI_TGZ is not a nikki bundle"
|
||
else
|
||
for _b in $NIKKI_BASES; do
|
||
log "nikki: downloading $_b/$_bundle"
|
||
wget -T 30 -qO- "$_b/$_bundle" | tar xzf - -C "$NIKKI_FEED" 2>/dev/null &&
|
||
[ -f "$NIKKI_FEED/Packages.gz" ] && break
|
||
log "nikki: not available there"
|
||
rm -rf "$NIKKI_FEED"
|
||
mkdir -p "$NIKKI_FEED"
|
||
done
|
||
fi
|
||
if [ ! -f "$NIKKI_FEED/Packages.gz" ]; then
|
||
nikki_feed_drop
|
||
die "nikki не скачался ($_bundle). На компьютере скачай его из
|
||
${NIKKI_BASES%% *}/$_bundle
|
||
(или https://github.com/nikkinikki-org/OpenWrt-nikki/releases/tag/$NIKKI_VERSION),
|
||
скопируй на роутер: scp -O $_bundle root@<роутер>:/tmp/
|
||
и запусти установку снова с NIKKI_TGZ=/tmp/$_bundle перед sh, например:
|
||
NIKKI_TGZ=/tmp/$_bundle sh /etc/nikki/kit/install.sh"
|
||
fi
|
||
# not needed by the kit, only takes RAM (upstream bundles have them)
|
||
rm -f "$NIKKI_FEED"/mihomo-alpha_*.ipk "$NIKKI_FEED"/luci-i18n-nikki-zh-*.ipk
|
||
opkg-key add "$KIT_DIR/router/nikki-key-build.pub" >/dev/null 2>&1 ||
|
||
log "warning: nikki: key not added, opkg may reject the feed signature"
|
||
echo "src/gz nikki_kit file://$NIKKI_FEED" > "$NIKKI_FEED_CONF"
|
||
# the feed points into RAM: never leave it behind, also after die
|
||
trap nikki_feed_drop EXIT
|
||
}
|
||
|
||
cmd_install() {
|
||
command -v opkg >/dev/null 2>&1 || die "нет opkg: OpenWrt 25.12+ (apk) kit пока не поддерживает"
|
||
_nikki_new=
|
||
if [ ! -x /etc/init.d/nikki ]; then
|
||
nikki_feed
|
||
_nikki_new=1
|
||
fi
|
||
opkg update
|
||
if [ -n "$_nikki_new" ]; then
|
||
# mihomo-meta named: nikki needs a "mihomo", and the feed also lists mihomo-alpha
|
||
_luci=
|
||
[ -d /www/luci-static/resources ] && _luci="luci-app-nikki luci-i18n-nikki-ru"
|
||
opkg_fit mihomo-meta nikki $_luci
|
||
nikki_feed_drop
|
||
trap - EXIT
|
||
[ -x /etc/init.d/nikki ] || die "nikki не установился, ошибки opkg выше"
|
||
fi
|
||
for p in curl oath-toolkit; do
|
||
opkg list-installed | grep -q "^$p " || opkg_fit "$p"
|
||
done
|
||
# curl newer than libcurl -> "Error relocating ... symbol not found"
|
||
curl --version >/dev/null 2>&1 || opkg install --force-reinstall libcurl4 curl
|
||
nikki_defaults
|
||
install_files
|
||
cmd_fix
|
||
}
|
||
|
||
# --- packages from files (opkg --force-space) --------------------------------
|
||
# opkg compares the full size of the new packages with the free space and does not
|
||
# count what the replaced old versions free, so on a small /overlay an upgrade of
|
||
# nikki / mihomo-meta stops with "not enough space" although it fits. pkg-install
|
||
# counts itself - free space + files of the installed versions that live in
|
||
# /overlay (not in /rom) against Installed-Size + PKG_RESERVE_KB - and only then
|
||
# runs --force-space, with nikki stopped: a running core keeps its deleted file on
|
||
# flash until it exits.
|
||
PKG_RESERVE_KB=${PKG_RESERVE_KB:-2048}
|
||
OPKG_INFO=${OPKG_INFO:-/usr/lib/opkg/info}
|
||
OVERLAY_UPPER=${OVERLAY_UPPER:-/overlay/upper}
|
||
|
||
# ipk_field <ipk> <Field>: from the control file (.ipk = tar.gz of control.tar.gz + data.tar.gz)
|
||
ipk_field() {
|
||
_d=$(mktemp -d /tmp/mihomo-kit-ipk.XXXXXX) || return 1
|
||
tar -xzOf "$1" ./control.tar.gz > "$_d/c.tgz" 2>/dev/null ||
|
||
tar -xzOf "$1" control.tar.gz > "$_d/c.tgz" 2>/dev/null
|
||
tar -xzf "$_d/c.tgz" -C "$_d" 2>/dev/null
|
||
sed -n "s/^$2: *//p" "$_d/control" 2>/dev/null | head -n 1
|
||
rm -rf "$_d"
|
||
}
|
||
|
||
# pkg_freed_kb <package>: KB the installed version's files take in the overlay
|
||
# (files of the firmware in /rom stay there after an upgrade)
|
||
pkg_freed_kb() {
|
||
_up=$OVERLAY_UPPER
|
||
[ -d "$_up" ] || _up=""
|
||
[ -f "$OPKG_INFO/$1.list" ] || { echo 0; return 0; }
|
||
cut -f1 "$OPKG_INFO/$1.list" | while IFS= read -r _p; do
|
||
[ -f "$_up$_p" ] && [ ! -L "$_up$_p" ] && du -k "$_up$_p"
|
||
done | awk '{s += $1} END {print s + 0}'
|
||
}
|
||
|
||
cmd_pkg_install() {
|
||
[ $# -gt 0 ] || die "usage: pkg-install <file.ipk>..."
|
||
_need=0 _freed=0
|
||
for _f in "$@"; do
|
||
[ -f "$_f" ] || die "no file $_f"
|
||
_pkg=$(ipk_field "$_f" Package)
|
||
_size=$(ipk_field "$_f" Installed-Size)
|
||
case "$_size" in '' | *[!0-9]*) die "$_f: not an .ipk (no Package / Installed-Size in its control)" ;; esac
|
||
[ -n "$_pkg" ] || die "$_f: not an .ipk (no Package / Installed-Size in its control)"
|
||
_kb=$(((_size + 1023) / 1024))
|
||
_old=$(pkg_freed_kb "$_pkg")
|
||
log "$_pkg $(ipk_field "$_f" Version): needs $_kb KB, the installed version frees $_old KB"
|
||
_need=$((_need + _kb)) _freed=$((_freed + _old))
|
||
done
|
||
_free=$(df -k / 2>/dev/null | awk 'NR==2 {print $4}')
|
||
_left=$((${_free:-0} + _freed - _need))
|
||
log "flash: free ${_free:-?} KB + freed $_freed KB - needed $_need KB = $_left KB left (reserve $PKG_RESERVE_KB KB)"
|
||
[ "$_left" -ge "$PKG_RESERVE_KB" ] ||
|
||
die "not enough flash, nothing installed (free $((PKG_RESERVE_KB - _left)) KB more)"
|
||
/etc/init.d/nikki stop 2>/dev/null
|
||
_rc=0
|
||
opkg install --force-space "$@" || _rc=$?
|
||
# a nikki upgrade replaces /etc/init.d/nikki (the kit's lines are gone): fix puts
|
||
# them back, checks the core and starts nikki - also after a failed install
|
||
cmd_fix
|
||
[ "$_rc" = 0 ] || die "opkg install failed (rc $_rc), see above; nikki is started again"
|
||
log "installed; free flash now $(df -k / 2>/dev/null | awk 'NR==2 {print $4}') KB"
|
||
}
|
||
|
||
cmd_fix() {
|
||
core_fetch || true
|
||
/etc/init.d/nikki stop 2>/dev/null
|
||
core_install
|
||
patch_init
|
||
fix_reserved
|
||
wan_metrics
|
||
dns_rebind_exempt
|
||
/etc/init.d/nikki start
|
||
core_confirm || true
|
||
}
|
||
|
||
# --- setup wizard -----------------------------------------------------------
|
||
|
||
: "${TTY_IN:=/dev/tty}" "${TTY_OUT:=/dev/tty}"
|
||
|
||
# ask VAR "question" [default]
|
||
ask() {
|
||
printf '%s%s: ' "$2" "${3:+ [$3]}" > "$TTY_OUT"
|
||
read -r _a < "$TTY_IN" || _a=""
|
||
eval "$1=\${_a:-\${3:-}}"
|
||
}
|
||
|
||
# ask_secret VAR "question" (no echo)
|
||
ask_secret() {
|
||
printf '%s: ' "$2" > "$TTY_OUT"
|
||
stty -echo < "$TTY_IN" 2>/dev/null
|
||
read -r _a < "$TTY_IN" || _a=""
|
||
stty echo < "$TTY_IN" 2>/dev/null
|
||
echo > "$TTY_OUT"
|
||
eval "$1=\$_a"
|
||
}
|
||
|
||
# yesno VAR "question" y|n -> VAR=1|0
|
||
yesno() {
|
||
while :; do
|
||
ask _yn "$2 (y/n)" "$3"
|
||
case "$_yn" in
|
||
y | Y | yes | д | Д) eval "$1=1"; return ;;
|
||
n | N | no | н | Н) eval "$1=0"; return ;;
|
||
esac
|
||
done
|
||
}
|
||
|
||
# check_boot_links: every BOOT_LINKS link parses (host, uuid, sni, pbk, sid)
|
||
check_boot_links() {
|
||
set -f
|
||
for _l in $BOOT_LINKS; do
|
||
vless_parse "$_l"
|
||
[ -n "$_vs_server" ] && [ -n "$_vs_uuid" ] && [ -n "$_vs_sni" ] && [ -n "$_vs_pbk" ] && [ -n "$_vs_sid" ] ||
|
||
die "не разобрал vless-ссылку (нужны host, uuid, sni, pbk, sid): ${_l%%\?*}"
|
||
done
|
||
set +f
|
||
}
|
||
|
||
q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
|
||
|
||
wizard() {
|
||
{
|
||
echo
|
||
echo "== mihomo-kit: профиль роутера =="
|
||
echo "Ответы сохранятся в $PROFILES_D/common.env (chmod 600)."
|
||
echo
|
||
} > "$TTY_OUT"
|
||
|
||
ask BOOT_LINKS "BOOT: vless:// ссылки seed-нод через пробел (пусто = без BOOT)"
|
||
BOOT=0
|
||
if [ -n "$BOOT_LINKS" ]; then
|
||
check_boot_links
|
||
BOOT=1
|
||
fi
|
||
|
||
echo "Подписки: по одной; пустой URL — конец." > "$TTY_OUT"
|
||
SUBS="" _n=0 _any_hwid=0
|
||
while :; do
|
||
ask _u "sub$_n URL"
|
||
[ -n "$_u" ] || break
|
||
SUBS="${SUBS:+$SUBS }$_u"
|
||
if [ "$BOOT" = 1 ]; then
|
||
ask _p " качать через (BOOT-AUTO/BOOT/DIRECT/FOREIGN)" BOOT-AUTO
|
||
else
|
||
ask _p " качать через (BOOT-AUTO/DIRECT/FOREIGN)" BOOT-AUTO
|
||
fi
|
||
eval "SUB${_n}_PROXY=\$_p"
|
||
yesno _hw " HWID-заголовки (x-hwid, x-device-os, ...; для подписок с лимитом устройств)" n
|
||
eval "SUB${_n}_HWID=\$_hw"
|
||
[ "$_hw" = 1 ] && _any_hwid=1
|
||
_n=$((_n + 1))
|
||
done
|
||
[ -n "$SUBS" ] || die "нужна хотя бы одна подписка"
|
||
if [ "$_any_hwid" = 1 ]; then
|
||
echo "HWID (общий для всех подписок с HWID):" > "$TTY_OUT"
|
||
[ -f /etc/openwrt_release ] && . /etc/openwrt_release
|
||
ask HWID_UA " User-Agent" "v2rayN/9.99"
|
||
ask HWID_OS " x-device-os" "OpenWrt"
|
||
ask HWID_OS_VER " x-ver-os" "${DISTRIB_RELEASE:-}"
|
||
ask HWID_MODEL " x-device-model" "$(cat /tmp/sysinfo/model 2>/dev/null)"
|
||
ask HWID_ID " x-hwid (если провайдер уже знает устройство — тот же)" \
|
||
"$(cat /sys/class/net/br-lan/address 2>/dev/null | md5sum | cut -c1-16)"
|
||
fi
|
||
|
||
yesno TORRENT "Торренты через TORRENT-SEL (порты 20000-20199)" n
|
||
yesno PUSH "Пуши (APNs, FCM) через группу PUSH" n
|
||
ask RU_IPS "Доп. IP через RU (CIDR через пробел)" ""
|
||
ask FOREIGN_IPS "Доп. IP через FOREIGN (CIDR через пробел)" ""
|
||
ask RU_DOMAINS "Доп. домены через RU (через пробел, с поддоменами)" ""
|
||
ask FOREIGN_DOMAINS "Доп. домены через FOREIGN (через пробел, с поддоменами)" ""
|
||
|
||
yesno OPENVPN "OpenVPN (рабочая или учебная сеть по файлу .ovpn)" n
|
||
if [ "$OPENVPN" = 1 ]; then
|
||
while [ ! -f "$NIKKI_DIR/openvpn.ovpn" ]; do
|
||
ask _dummy "Положи .ovpn в $NIKKI_DIR/openvpn.ovpn (scp -O file.ovpn root@router:$NIKKI_DIR/openvpn.ovpn) и нажми Enter"
|
||
done
|
||
ask VPN_USERNAME " логин"
|
||
ask_secret VPN_PASSWORD " пароль (без одноразового кода)"
|
||
ask_secret TOTP_SECRET " TOTP-секрет для одноразовых кодов, base32 из QR (пусто — без кодов)"
|
||
ask OVPN_ROUTES " сети через VPN (CIDR через пробел)" "$(ovpn_routes_of "$NIKKI_DIR/openvpn.ovpn")"
|
||
fi
|
||
|
||
yesno CSQTT "CSQTT (star-panel-csqtt, интерфейс csqtt0): группа UPLINK" n
|
||
|
||
yesno TAILSCALE "Tailscale" n
|
||
if [ "$TAILSCALE" = 1 ]; then
|
||
ask TS_HOSTNAME " имя ноды" "$(uci -q get 'system.@system[0].hostname' | tr 'A-Z' 'a-z')-mihomo"
|
||
ask TS_DOMAINS " split-DNS домены тейлнета кроме *.ts.net (через пробел)" ""
|
||
fi
|
||
|
||
write_config
|
||
}
|
||
|
||
# keys write_config owns; any other KEY=value lines (added by hand) are kept
|
||
COMMON_KEYS='TARGET|SUBS|SUB[0-9]*_[A-Z0-9_]*(PROXY|HWID|DISABLED)|HWID_[A-Z_]+|BOOT|BOOT_[A-Z]+|TORRENT|PUSH|RU_IPS|FOREIGN_IPS|RU_DOMAINS|FOREIGN_DOMAINS|OPENVPN|OVPN_ROUTES|TAILSCALE|TS_HOSTNAME|TS_DOMAINS|CSQTT'
|
||
VPN_KEYS='VPN_USERNAME|VPN_PASSWORD|TOTP_SECRET|PASS_FORMAT'
|
||
|
||
# other_keys <file> <keys-regex>
|
||
other_keys() {
|
||
grep -E '^[A-Za-z_][A-Za-z0-9_]*=' "$1" 2>/dev/null | grep -vE "^($2)="
|
||
}
|
||
|
||
# hand-added keys of common.env; the old SUB<index>_* ones are renamed to
|
||
# SUB_<ID>_* by the subscription order of that file
|
||
common_other_keys() {
|
||
_f=$PROFILES_D/common.env
|
||
[ -f "$_f" ] || return 0
|
||
_old_ids=$(
|
||
SUBS=
|
||
. "$_f"
|
||
sub_pairs
|
||
for _p in $SUB_PAIRS; do echo "${_p%%=*}"; done
|
||
)
|
||
other_keys "$_f" "$COMMON_KEYS" | while IFS= read -r _l; do
|
||
_n=${_l%%_*}
|
||
_n=${_n#SUB}
|
||
case "$_l" in
|
||
SUB[0-9]*_*)
|
||
case "$_n" in
|
||
'' | *[!0-9]*) ;;
|
||
*)
|
||
_id=$(echo "$_old_ids" | sed -n "$((_n + 1))p")
|
||
[ -n "$_id" ] && _l="SUB_$(echo "$_id" | tr 'a-z' 'A-Z')_${_l#*_}"
|
||
;;
|
||
esac
|
||
;;
|
||
esac
|
||
echo "$_l"
|
||
done
|
||
}
|
||
|
||
# common.env (+ openvpn.env) from the variables the wizard / configure set;
|
||
# per-subscription values come as SUB<index>_PROXY/HWID (index in SUBS).
|
||
# Keys only the LuCI form sets (own hysteria2 servers HY2, HY2_<NAME>_*, MY_IPS,
|
||
# MY_DOMAINS, LOCAL_HOSTS, MY_LINKS, LITE, check URLs, SERVICES + SVC_<NAME>_*, POOLS + POOL_<NAME>_*) are rewritten only with FORM=1; the terminal wizard keeps them.
|
||
write_config() {
|
||
umask 077
|
||
_any_hwid=0
|
||
[ "${FORM:-0}" = 1 ] && COMMON_KEYS="$COMMON_KEYS|HY2|HY2_[A-Z0-9_]+|MY_IPS|MY_DOMAINS|LOCAL_HOSTS|MY_LINKS|LITE|LITE_GOMEMLIMIT|OVPN_CHECK_URL|TS_CHECK_URL|MOBILE|MY_NODE_[0-9]+|SERVICES|SVC_[A-Z0-9_]+|POOLS|POOL_[A-Z0-9_]+"
|
||
_others=$(common_other_keys)
|
||
sub_pairs
|
||
{
|
||
echo "# written by mihomo-kit.sh (setup / LuCI); edit and run: mihomo-kit.sh build"
|
||
echo "TARGET=router"
|
||
echo "SUBS=$(q "$SUBS")"
|
||
_i=0
|
||
for _pr in $SUB_PAIRS; do
|
||
_K=$(echo "${_pr%%=*}" | tr 'a-z' 'A-Z')
|
||
_p=$(sub_get "$_i" "${_pr%%=*}" PROXY) _hw=$(sub_get "$_i" "${_pr%%=*}" HWID)
|
||
[ "$_p" != BOOT ] || [ "$BOOT" = 1 ] || _p=BOOT-AUTO
|
||
[ -n "$_p" ] && [ "$_p" != BOOT-AUTO ] && echo "SUB_${_K}_PROXY=$(q "$_p")"
|
||
[ "$_hw" = 1 ] && echo "SUB_${_K}_HWID=1" && _any_hwid=1
|
||
sub_off "$_i" "${_pr%%=*}" && echo "SUB_${_K}_DISABLED=1"
|
||
_i=$((_i + 1))
|
||
done
|
||
if [ "$_any_hwid" = 1 ]; then
|
||
for v in HWID_UA HWID_OS HWID_OS_VER HWID_MODEL HWID_ID; do
|
||
eval "echo \"$v=\$(q \"\${$v:-}\")\""
|
||
done
|
||
fi
|
||
echo "BOOT=$BOOT"
|
||
[ "$BOOT" = 1 ] && echo "BOOT_LINKS=$(q "$BOOT_LINKS")"
|
||
echo "TORRENT=$TORRENT"
|
||
echo "PUSH=${PUSH:-0}"
|
||
for v in RU_IPS FOREIGN_IPS RU_DOMAINS FOREIGN_DOMAINS; do
|
||
eval "_v=\${$v:-}"
|
||
[ -n "$_v" ] || [ "$v" = RU_IPS ] && echo "$v=$(q "$_v")"
|
||
done
|
||
echo "OPENVPN=$OPENVPN"
|
||
[ -n "${OVPN_ROUTES:-}" ] && echo "OVPN_ROUTES=$(q "$OVPN_ROUTES")"
|
||
echo "CSQTT=${CSQTT:-0}"
|
||
echo "TAILSCALE=$TAILSCALE"
|
||
[ "$TAILSCALE" = 1 ] && echo "TS_HOSTNAME=$(q "$TS_HOSTNAME")" && echo "TS_DOMAINS=$(q "$TS_DOMAINS")"
|
||
if [ "${FORM:-0}" = 1 ]; then
|
||
[ -n "${OVPN_CHECK_URL:-}" ] && echo "OVPN_CHECK_URL=$(q "$OVPN_CHECK_URL")"
|
||
[ -n "${TS_CHECK_URL:-}" ] && echo "TS_CHECK_URL=$(q "$TS_CHECK_URL")"
|
||
[ "${MOBILE:-0}" = 1 ] && echo "MOBILE=1"
|
||
[ "${LITE:-0}" = 1 ] && echo "LITE=1"
|
||
[ -n "${LITE_GOMEMLIMIT:-}" ] && echo "LITE_GOMEMLIMIT=$(q "$LITE_GOMEMLIMIT")"
|
||
echo "HY2=$(q "$HY2")"
|
||
[ -n "${MY_IPS:-}" ] && echo "MY_IPS=$(q "$MY_IPS")"
|
||
[ -n "${MY_DOMAINS:-}" ] && echo "MY_DOMAINS=$(q "$MY_DOMAINS")"
|
||
[ -n "${LOCAL_HOSTS:-}" ] && echo "LOCAL_HOSTS=$(q "$LOCAL_HOSTS")"
|
||
[ -n "${MY_LINKS:-}" ] && echo "MY_LINKS=$(q "$MY_LINKS")"
|
||
printf '%s\n' "${MY_NODE_ENTRIES:-}" | grep . | awk '{ print NR "\t" $0 }' | while IFS=' ' read -r _mk _ml; do
|
||
echo "MY_NODE_$_mk=$(q "$_ml")"
|
||
done
|
||
[ -n "${POOLS:-}" ] && echo "POOLS=$(q "$POOLS")"
|
||
for _s in ${POOLS:-}; do
|
||
_k=$(pool_key "$_s")
|
||
for v in TYPE SERVERS SUBS FILTER EXCLUDE UPLINK; do
|
||
eval "_v=\${${_k}_$v:-}"
|
||
[ -n "$_v" ] && echo "${_k}_$v=$(q "$_v")"
|
||
done
|
||
done
|
||
[ -n "${SERVICES:-}" ] && echo "SERVICES=$(q "$SERVICES")"
|
||
for _s in ${SERVICES:-}; do
|
||
_k=$(svc_key "$_s")
|
||
for v in GEOSITE DOMAINS IPS VIA CHAIN SERVER PROVIDER; do
|
||
eval "_v=\${${_k}_$v:-}"
|
||
[ -n "$_v" ] && echo "${_k}_$v=$(q "$_v")"
|
||
done
|
||
done
|
||
for _n in $HY2; do
|
||
_k=$(hy2_key "$_n")
|
||
for v in SERVER PORT PASSWORD OBFS_PASSWORD SNI INSECURE UP DOWN; do
|
||
eval "_v=\${${_k}_$v:-}"
|
||
[ -n "$_v" ] && echo "${_k}_$v=$(q "$_v")"
|
||
done
|
||
done
|
||
fi
|
||
[ -n "$_others" ] && echo "$_others"
|
||
true
|
||
} > "$PROFILES_D/common.env.tmp" && mv "$PROFILES_D/common.env.tmp" "$PROFILES_D/common.env"
|
||
if [ "$OPENVPN" = 1 ]; then
|
||
{
|
||
echo "# written by mihomo-kit.sh (setup / LuCI)"
|
||
echo "VPN_USERNAME=$(q "$VPN_USERNAME")"
|
||
echo "VPN_PASSWORD=$(q "$VPN_PASSWORD")"
|
||
[ -n "${TOTP_SECRET:-}" ] && echo "TOTP_SECRET=$(q "$TOTP_SECRET")"
|
||
[ -n "${PASS_FORMAT:-}" ] && [ "$PASS_FORMAT" != auto ] && echo "PASS_FORMAT=$(q "$PASS_FORMAT")"
|
||
other_keys "$NIKKI_DIR/openvpn.env" "$VPN_KEYS"
|
||
true
|
||
} > "$NIKKI_DIR/openvpn.env.tmp" && mv "$NIKKI_DIR/openvpn.env.tmp" "$NIKKI_DIR/openvpn.env"
|
||
fi
|
||
for f in "$KIT_DIR"/presets/*.env; do
|
||
[ -f "$PROFILES_D/${f##*/}" ] || cp "$f" "$PROFILES_D/"
|
||
done
|
||
umask 022
|
||
}
|
||
|
||
# "<id> <SUBS word>" per subscription of $SUBS (for the LuCI form)
|
||
cmd_sub_ids() {
|
||
SUBS=${SUBS:-}
|
||
sub_pairs
|
||
set -f
|
||
# shellcheck disable=SC2086
|
||
_ws=$(printf '%s ' $SUBS)
|
||
for _pr in $SUB_PAIRS; do
|
||
_w=${_ws%% *}
|
||
_ws=${_ws#"$_w"}
|
||
_ws=${_ws# }
|
||
echo "${_pr%%=*} $_w"
|
||
done
|
||
}
|
||
|
||
# Settings from the LuCI form: <env> holds BOOT_LINKS, SUBS, SUB<i>_PROXY/HWID,
|
||
# HWID_*, TORRENT, PUSH, RU_IPS, FOREIGN_IPS, MY_IPS, *_DOMAINS, OPENVPN, CSQTT, VPN_* (empty secrets = keep), TAILSCALE, TS_*,
|
||
# FORM=1, OVPN_ROUTES, OVPN_CHECK_URL, PASS_FORMAT, TS_CHECK_URL, HY2 + HY2_<NAME>_*,
|
||
# SERVICES + SVC_<NAME>_*.
|
||
# Validates, writes common.env/openvpn.env, builds and restarts the current profile.
|
||
cmd_configure() {
|
||
[ -f "${1:-}" ] || die "usage: configure <env>"
|
||
# saved OpenVPN secrets stay unless the form sends new ones
|
||
[ -f "$NIKKI_DIR/openvpn.env" ] && . "$NIKKI_DIR/openvpn.env"
|
||
# the saved networks and [MY] node entries unless the form sends them
|
||
OVPN_ROUTES=$(sed -n "s/^OVPN_ROUTES=//p" "$PROFILES_D/common.env" 2>/dev/null | tail -n 1 | tr -d "'\"")
|
||
MY_NODE_ENTRIES=$( (. "$PROFILES_D/common.env" 2>/dev/null; my_nodes_join) )
|
||
. "$1"
|
||
rm -f "$1"
|
||
BOOT=0 BOOT_LINKS=${BOOT_LINKS:-}
|
||
if [ -n "$BOOT_LINKS" ]; then
|
||
check_boot_links
|
||
BOOT=1
|
||
fi
|
||
[ -n "${SUBS:-}" ] || die "нужна хотя бы одна подписка"
|
||
if [ "$OPENVPN" = 1 ]; then
|
||
[ -f "$NIKKI_DIR/openvpn.ovpn" ] || die "OpenVPN: нет файла .ovpn ($NIKKI_DIR/openvpn.ovpn)"
|
||
[ -n "${VPN_USERNAME:-}" ] && [ -n "${VPN_PASSWORD:-}" ] || die "OpenVPN: нужны логин и пароль"
|
||
# empty: the routes the .ovpn names itself
|
||
: "${OVPN_ROUTES:=$(ovpn_routes_of "$NIKKI_DIR/openvpn.ovpn")}"
|
||
[ -n "$OVPN_ROUTES" ] ||
|
||
die "OpenVPN: укажи сети, которые идут через VPN (в файле .ovpn нет строк route)"
|
||
fi
|
||
write_config
|
||
log "saved $PROFILES_D/common.env"
|
||
cmd_apply
|
||
}
|
||
|
||
# settings in profiles.d (+ openvpn.*) -> build, OpenVPN cron, restart the current
|
||
# profile, Tailscale login if needed (after configure / import)
|
||
cmd_apply() {
|
||
cmd_build
|
||
if grep -q '^OPENVPN=1' "$PROFILES_D/common.env"; then
|
||
enable_otp_cron
|
||
elif grep -qE "(ovpn|bmstu-otp)\.sh check" /etc/crontabs/root 2>/dev/null; then
|
||
sed -i -E '/(ovpn|bmstu-otp)\.sh check/d' /etc/crontabs/root
|
||
/etc/init.d/cron restart
|
||
log "removed ovpn.sh check from cron"
|
||
fi
|
||
cur=$(uci -q get nikki.config.profile)
|
||
cur=${cur#file:}
|
||
cur=${cur%.yaml}
|
||
[ -f "$PROFILES_D/$cur.env" ] || cur=main
|
||
cmd_use "$cur"
|
||
# Tailscale login only on the very first start (no node state yet); later it is
|
||
# the "login" button, so saving settings never replaces an existing node
|
||
if grep -q '^TAILSCALE=1' "$PROFILES_D/common.env" && [ ! -f "$TS_DIR/tailscaled.state" ]; then
|
||
cmd_ts_login
|
||
fi
|
||
true
|
||
}
|
||
|
||
# services <env>: the blocks <env> has (the graph page) replace those of common.env - with
|
||
# SERVICES= the services (SERVICES, SVC_<NAME>_*), with POOLS= the pools (POOLS, POOL_<NAME>_*);
|
||
# every profile must still render, else nothing changes; then build and apply
|
||
cmd_services() {
|
||
[ -f "${1:-}" ] || die "usage: services <env>"
|
||
_c=$PROFILES_D/common.env
|
||
[ -f "$_c" ] || die "no $_c: save the settings first"
|
||
_keys=""
|
||
grep -q '^SERVICES=' "$1" && _keys="SERVICES|SVC_[A-Z0-9_]+"
|
||
grep -q '^POOLS=' "$1" && _keys="${_keys:+$_keys|}POOLS|POOL_[A-Z0-9_]+"
|
||
[ -n "$_keys" ] || die "services: $1 has neither SERVICES= nor POOLS="
|
||
umask 077
|
||
{
|
||
grep -vE "^($_keys)=" "$_c"
|
||
grep -E "^($_keys)=" "$1"
|
||
} > "$_c.new"
|
||
rm -f "$1"
|
||
umask 022
|
||
for e in "$PROFILES_D"/*.env; do
|
||
n=${e##*/}
|
||
n=${n%.env}
|
||
[ "$n" = common ] && continue
|
||
if ! (cmd_render "$_c.new" "$e") > /dev/null; then
|
||
rm -f "$_c.new"
|
||
die "services not saved: profile $n does not build with them"
|
||
fi
|
||
done
|
||
mv "$_c.new" "$_c"
|
||
log "saved services: $(sed -n 's/^SERVICES=//p' "$_c" | tr -d "'"); pools: $(sed -n 's/^POOLS=//p' "$_c" | tr -d "'")"
|
||
cmd_apply
|
||
}
|
||
|
||
# Settings bundle: one text file with profiles.d/*.env, openvpn.env, openvpn.ovpn
|
||
# (secrets inside). Not in it: kit.env (core choice), the Tailscale node key,
|
||
# the phone link token - all per router.
|
||
EXPORT_HEAD='# mihomo-kit export v1'
|
||
cmd_export() {
|
||
echo "$EXPORT_HEAD $(uci -q get 'system.@system[0].hostname') $(date '+%Y-%m-%d %H:%M')"
|
||
for _f in "$PROFILES_D"/*.env "$NIKKI_DIR/openvpn.env" "$NIKKI_DIR/openvpn.ovpn" "$NIKKI_DIR/my-servers"; do
|
||
[ -f "$_f" ] || continue
|
||
echo "#%% file ${_f#"$NIKKI_DIR"/}"
|
||
cat "$_f"
|
||
[ -z "$(tail -c 1 "$_f")" ] || echo
|
||
done
|
||
}
|
||
|
||
# import <file> [--keep-local]: replace the settings with the bundle and apply;
|
||
# --keep-local keeps this router's TS_HOSTNAME and HWID_ID (node name, device id) and
|
||
# LOCAL_HOSTS (its LAN: the bundle's one is dropped when this router has none)
|
||
cmd_import() {
|
||
[ -f "${1:-}" ] || die "usage: import <file> [--keep-local]"
|
||
head -n 1 "$1" | grep -q "^$EXPORT_HEAD" || die "not a mihomo-kit export"
|
||
_files=$(sed -n 's/^#%% file //p' "$1")
|
||
echo "$_files" | grep -q '^profiles.d/common.env$' || die "no profiles.d/common.env in the export"
|
||
for _f in $_files; do
|
||
case "$_f" in
|
||
# bmstu.*: bundles of kits before 2026-11
|
||
profiles.d/*.env | openvpn.env | openvpn.ovpn | bmstu.env | bmstu.ovpn | my-servers) ;;
|
||
*) die "unexpected file in the export: $_f" ;;
|
||
esac
|
||
case "${_f#profiles.d/}" in */* | *[!A-Za-z0-9_.-]*) die "bad file name: $_f" ;; esac
|
||
done
|
||
# _drop: keys of the bundle replaced by this router's ones (LOCAL_HOSTS always)
|
||
_keep="" _drop=LOCAL_HOSTS
|
||
if [ "${2:-}" = --keep-local ]; then
|
||
for _k in TS_HOSTNAME HWID_ID LOCAL_HOSTS; do
|
||
_l=$(grep "^$_k=" "$PROFILES_D/common.env" 2>/dev/null | tail -n 1)
|
||
[ -n "$_l" ] || continue
|
||
_keep="$_keep$_l
|
||
"
|
||
[ "$_k" = LOCAL_HOSTS ] || _drop="$_drop|$_k"
|
||
done
|
||
fi
|
||
_tmp=$(mktemp -d)
|
||
mkdir -p "$_tmp/profiles.d"
|
||
awk -v d="$_tmp" '/^#%% file /{ f = d "/" $3; next } f { print > f }' "$1"
|
||
umask 077
|
||
rm -f "$PROFILES_D"/*.env
|
||
cp "$_tmp"/profiles.d/*.env "$PROFILES_D/"
|
||
if [ -f "$_tmp/bmstu.ovpn" ] && [ ! -f "$_tmp/openvpn.ovpn" ]; then
|
||
mv "$_tmp/bmstu.ovpn" "$_tmp/openvpn.ovpn"
|
||
ovpn_old_defaults "$PROFILES_D/common.env"
|
||
fi
|
||
[ -f "$_tmp/bmstu.env" ] && [ ! -f "$_tmp/openvpn.env" ] && mv "$_tmp/bmstu.env" "$_tmp/openvpn.env"
|
||
for _f in openvpn.env openvpn.ovpn my-servers; do
|
||
[ -f "$_tmp/$_f" ] && cp "$_tmp/$_f" "$NIKKI_DIR/$_f"
|
||
done
|
||
if [ "${2:-}" = --keep-local ]; then
|
||
grep -vE "^($_drop)=" "$PROFILES_D/common.env" > "$_tmp/common.env"
|
||
printf '%s' "$_keep" >> "$_tmp/common.env"
|
||
cp "$_tmp/common.env" "$PROFILES_D/common.env"
|
||
fi
|
||
chmod 600 "$PROFILES_D"/*.env
|
||
umask 022
|
||
rm -rf "$_tmp"
|
||
log "imported $(echo "$_files" | wc -l | tr -d ' ') files from: $(head -n 1 "$1" | cut -d' ' -f5-)"
|
||
# the upload from LuCI holds secrets
|
||
case "$1" in /tmp/mihomo-kit-import.*) rm -f "$1" ;; esac
|
||
cmd_apply
|
||
}
|
||
|
||
# install only; settings in LuCI (or questions here with --cli / without LuCI)
|
||
cmd_setup() {
|
||
cmd_install
|
||
if [ "${1:-}" != --cli ] && [ -d /www/luci-static/resources ]; then
|
||
_ip=$(uci -q get network.lan.ipaddr)
|
||
_ip=${_ip%%/*}
|
||
log ""
|
||
log "Установлено. Настройка — в браузере:"
|
||
log " http://${_ip:-<роутер>}/cgi-bin/luci/admin/services/mihomo-kit"
|
||
log " (LuCI → Службы → mihomo-kit; если пункта нет — выйди и войди снова)"
|
||
log "Вопросы в терминале вместо LuCI: mihomo-kit.sh setup --cli"
|
||
return 0
|
||
fi
|
||
[ -r "$TTY_IN" ] || die "setup --cli needs a terminal (run it over ssh)"
|
||
_redo=1
|
||
if [ -f "$PROFILES_D/common.env" ]; then
|
||
yesno _redo "$PROFILES_D/common.env уже есть. Ответить на вопросы заново" n
|
||
fi
|
||
[ "$_redo" = 1 ] && wizard
|
||
cmd_build
|
||
if grep -q "^OPENVPN=1" "$PROFILES_D/common.env"; then
|
||
enable_otp_cron
|
||
grep -q '^TOTP_SECRET=' "$NIKKI_DIR/openvpn.env" 2>/dev/null &&
|
||
echo "Код сейчас: $(ovpn.sh otp) — сверь с приложением-генератором" > "$TTY_OUT"
|
||
fi
|
||
_profiles=$(cd "$PROFILES_D" && ls *.env | sed 's/\.env$//' | grep -v '^common$' | tr '\n' ' ')
|
||
ask _start "Какой профиль включить ($_profiles)" main
|
||
cmd_use "$_start"
|
||
grep -q "^TAILSCALE=1" "$PROFILES_D/common.env" && cmd_ts_login
|
||
{
|
||
echo
|
||
echo "Готово. Дальше:"
|
||
echo " mihomo-kit.sh use main|whitelist переключить профиль"
|
||
echo " ovpn.sh off|on|status OpenVPN: выключить, включить, состояние"
|
||
grep -q "^TAILSCALE=1" "$PROFILES_D/common.env" &&
|
||
echo " mihomo-kit.sh ts-login ссылка для входа в Tailscale (если не вошёл)"
|
||
echo " mihomo-kit.sh fix после обновления пакета nikki"
|
||
} > "$TTY_OUT"
|
||
}
|
||
|
||
# kit_version <kit.tgz>: "<commit> <date>" into $KIT_DIR/VERSION. git archive
|
||
# (what the git server serves) puts the commit id into the first tar header.
|
||
kit_version() {
|
||
_sha=$(gunzip -c "$1" 2>/dev/null | head -c 1536 | tr -c 'a-z0-9=\n' '\n' |
|
||
grep '^comment=[0-9a-f]\{40\}$' | head -n 1 | cut -c9-15)
|
||
echo "${_sha:-?} $(date '+%Y-%m-%d %H:%M')" > "$KIT_DIR/VERSION"
|
||
}
|
||
|
||
# Latest commit of the KIT_URL branch (Gitea/Forgejo API). Prints lines:
|
||
# installed <sha>, latest <sha>, message <first line>, commit <url>, compare <url>
|
||
cmd_check_update() {
|
||
_repo=${KIT_URL%/archive/*}
|
||
_branch=${KIT_URL##*/archive/}
|
||
_branch=${_branch%.tar.gz}
|
||
_host=${_repo%/*/*}
|
||
_json=$(wget -q -T 10 -O - "$_host/api/v1/repos/${_repo#"$_host"/}/branches/$_branch") ||
|
||
die "no answer from $_host"
|
||
_id=$(jsonfilter -s "$_json" -e '@.commit.id') || die "unexpected answer from $_host"
|
||
_cur=$(cut -d' ' -f1 "$KIT_DIR/VERSION" 2>/dev/null)
|
||
_cur=${_cur%-dirty}
|
||
echo "installed ${_cur:-?}"
|
||
echo "latest $(echo "$_id" | cut -c1-7)"
|
||
echo "message $(jsonfilter -s "$_json" -e '@.commit.message' | head -n 1)"
|
||
echo "commit $_repo/commit/$_id"
|
||
case "$_cur" in
|
||
'' | '?') ;;
|
||
*) echo "compare $_repo/compare/$_cur...$_id" ;;
|
||
esac
|
||
}
|
||
|
||
# core <stock|official|kit>: save the choice in kit.env (other keys kept) and apply it
|
||
cmd_core() {
|
||
case "${1:-}" in stock | official | kit) ;; *) die "usage: core stock|official|kit" ;; esac
|
||
touch "$KIT_ENV"
|
||
grep -vE '^(CORE|MIHOMO_VERSION|MIHOMO_BASE)=' "$KIT_ENV" > "$KIT_ENV.tmp"
|
||
echo "CORE=$1" >> "$KIT_ENV.tmp"
|
||
mv "$KIT_ENV.tmp" "$KIT_ENV"
|
||
log "core choice: $1"
|
||
exec sh "$SELF" fix
|
||
}
|
||
|
||
# for the LuCI select: "key value" lines
|
||
cmd_core_info() {
|
||
echo "choice $CORE"
|
||
echo "pinned $(grep -q '^MIHOMO_VERSION=' "$KIT_ENV" 2>/dev/null && echo 1 || echo 0)"
|
||
echo "wanted $MIHOMO_VERSION"
|
||
echo "ok $(core_ok && echo 1 || echo 0)"
|
||
echo "stock $("$STOCK_CORE" -v 2>/dev/null | awk '{print $3; exit}')"
|
||
echo "official $CORE_OFFICIAL"
|
||
echo "kit $CORE_KIT"
|
||
_bin=$(command -v mihomo || echo /usr/bin/mihomo)
|
||
echo "free_kb $(df -k "${_bin%/*}" 2>/dev/null | awk 'NR==2 {print $4}')"
|
||
echo "need_kb $CORE_NEED_KB"
|
||
}
|
||
|
||
cmd_update() {
|
||
_apply=${1:-}
|
||
tmp=$(mktemp -d)
|
||
log "downloading $KIT_URL"
|
||
wget -qO "$tmp/kit.tgz" "$KIT_URL" || die "download failed"
|
||
tar xzf "$tmp/kit.tgz" -C "$tmp" || die "bad archive"
|
||
src=$(dirname "$(find "$tmp" -path '*/router/mihomo-kit.sh' | head -n 1)")
|
||
[ -n "$src" ] && [ "$src" != . ] || die "no router/mihomo-kit.sh in the archive"
|
||
src=${src%/router}
|
||
for d in templates presets router luci; do
|
||
rm -rf "${KIT_DIR:?}/$d"
|
||
[ -d "$src/$d" ] && cp -r "$src/$d" "$KIT_DIR/$d"
|
||
done
|
||
kit_version "$tmp/kit.tgz"
|
||
rm -rf "$tmp"
|
||
log "kit version $(cat "$KIT_DIR/VERSION")"
|
||
# the rest runs from the new script: this one is the old version
|
||
exec sh "$KIT_DIR/router/mihomo-kit.sh" post-update $_apply
|
||
}
|
||
|
||
cmd_post_update() {
|
||
install_files
|
||
cmd_build
|
||
cur=$(uci -q get nikki.config.profile)
|
||
cur=$(basename "${cur#file:}" .yaml)
|
||
if [ "${1:-}" != --apply ]; then
|
||
log "kit updated; to apply: mihomo-kit.sh use $cur"
|
||
return 0
|
||
fi
|
||
# a new kit may pin another core version
|
||
core_ok || cmd_fix
|
||
core_ok || auto_log "core $MIHOMO_VERSION not installed yet, retried at the next auto-update"
|
||
[ -f "$PROFILES_OUT/$cur.yaml" ] && cmd_use "$cur"
|
||
auto_log "updated to $(cut -d' ' -f1 "$KIT_DIR/VERSION"), profile $cur restarted"
|
||
}
|
||
|
||
AUTO_CRON='0 4 * * * /usr/bin/mihomo-kit.sh auto-update'
|
||
AUTO_LOG=$NIKKI_DIR/kit/auto-update.log
|
||
|
||
# auto_log <text>: last runs for the LuCI page (and syslog)
|
||
auto_log() {
|
||
logger -t mihomo-kit "auto-update: $*" 2>/dev/null
|
||
echo "$(date '+%Y-%m-%d %H:%M') $*" >> "$AUTO_LOG"
|
||
tail -n 20 "$AUTO_LOG" > "$AUTO_LOG.tmp" && mv "$AUTO_LOG.tmp" "$AUTO_LOG"
|
||
}
|
||
|
||
# auto-update on|off: the cron line; no argument: update if the server has a newer commit
|
||
cmd_auto_update() {
|
||
case "${1:-}" in
|
||
on | off)
|
||
sed -i '/mihomo-kit.sh auto-update/d' /etc/crontabs/root 2>/dev/null
|
||
[ "$1" = on ] && echo "$AUTO_CRON" >> /etc/crontabs/root
|
||
/etc/init.d/cron restart
|
||
log "auto-update $1"
|
||
return 0
|
||
;;
|
||
esac
|
||
export PATH=/usr/sbin:/usr/bin:/sbin:/bin:$PATH
|
||
if ! _out=$(cmd_check_update 2>&1); then
|
||
auto_log "check failed: $(echo "$_out" | tail -n 1)"
|
||
return 1
|
||
fi
|
||
_cur=$(echo "$_out" | sed -n 's/^installed //p')
|
||
_new=$(echo "$_out" | sed -n 's/^latest //p')
|
||
case "$_cur" in
|
||
"$_new"*)
|
||
# the kit is current, but its core may not have got through last time
|
||
# (release published after the kit, download failed): retry it, only
|
||
# when it is there, so a missing release does not restart nikki nightly
|
||
if core_ok; then
|
||
auto_log "up to date ($_new)"
|
||
elif core_available; then
|
||
auto_log "up to date ($_new), installing core $MIHOMO_VERSION"
|
||
cmd_fix
|
||
core_ok || auto_log "core $MIHOMO_VERSION still not installed"
|
||
else
|
||
auto_log "up to date ($_new), core $MIHOMO_VERSION not downloadable yet"
|
||
fi
|
||
return 0
|
||
;;
|
||
esac
|
||
auto_log "updating $_cur -> $_new"
|
||
cmd_update --apply
|
||
}
|
||
|
||
case "${1:-}" in
|
||
render) shift; cmd_render "$@" ;;
|
||
build) shift; cmd_build "$@" ;;
|
||
use) shift; cmd_use "$@" ;;
|
||
setup) shift; cmd_setup "$@" ;;
|
||
configure) shift; cmd_configure "$@" ;;
|
||
apply) cmd_apply ;;
|
||
services) shift; cmd_services "$@" ;;
|
||
export) cmd_export ;;
|
||
import) shift; cmd_import "$@" ;;
|
||
mobile) shift; cmd_mobile "$@" ;;
|
||
sub-ids) cmd_sub_ids ;;
|
||
# the core version the kit wants on this router (LuCI)
|
||
core-wanted) echo "$MIHOMO_VERSION" ;;
|
||
update) shift; cmd_update "$@" ;;
|
||
core) shift; cmd_core "$@" ;;
|
||
core-info) cmd_core_info ;;
|
||
pkg-install) shift; cmd_pkg_install "$@" ;;
|
||
auto-update) shift; cmd_auto_update "$@" ;;
|
||
check-update) cmd_check_update ;;
|
||
post-update) shift; cmd_post_update "$@" ;;
|
||
install) cmd_install ;;
|
||
fix) cmd_fix ;;
|
||
ts-login) shift; cmd_ts_login "$@" ;;
|
||
csqtt) shift; cmd_csqtt "$@" ;;
|
||
*) sed -n '2,34p' "$SELF" >&2; exit 2 ;;
|
||
esac
|