mihomo-kit/router/mihomo-kit.sh
2026-10-15 14:46:58 +03:00

1474 lines
51 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/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 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
# (-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 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.32
CORE_KIT=v1.19.32-ts4
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}"
log() { echo "$*" >&2; }
die() { log "error: $*"; exit 1; }
# --- rendering --------------------------------------------------------------
# Template syntax (same in web/engine.js):
# file NN-<module>[.<tag>...][.each].yaml included if module and tags are active;
# .each = once per item of the module:
# sub - subscription, hy2 - own server
# 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
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:=}"
: "${GEOIP_URL:=https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/geoip.dat}"
: "${GEOSITE_URL:=https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/geosite.dat}"
: "${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:=bmstu}" "${OVPN_GROUP:=BMSTU}" "${OVPN_SERVER_HOST:=openvpn4.bmstu.ru}"
: "${OVPN_SERVER_IPS:=195.19.40.7 195.19.33.86}"
: "${OVPN_ROUTES:=172.16.0.0/16 172.19.33.0/24 195.19.32.0/19}"
: "${OVPN_CHECK_URL:=https://eu.bmstu.ru}" "${TS_CHECK_URL:=http://100.69.216.50:8080}"
: "${CSQTT:=0}" "${CSQTT_IFACE:=csqtt0}" "${CSQTT_PROCESS:=csqtt}"
}
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 "
fi
# CSQTT tunnel (star-panel-csqtt): first (default) in MAIN
CSQTT_MAIN=""
case "$TAGS" in *" csqtt "*) CSQTT_MAIN="CSQTT, " ;; esac
SUB_LIST="" _i=0
for _p in $SUB_PAIRS; do
sub_off "$_i" "${_p%%=*}" || SUB_LIST="${SUB_LIST:+$SUB_LIST, }${_p%%=*}"
_i=$((_i + 1))
done
# own hysteria2 servers: HY2_LIST "a, b" (group MY), HY2_MAIN "MY, " (MAIN)
HY2_LIST="" HY2_MAIN=""
for _n in $HY2; do
HY2_LIST="${HY2_LIST:+$HY2_LIST, }$_n"
done
[ -n "$HY2" ] && TAGS="$TAGS hy2 " HY2_MAIN="MY, "
# 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 *" hy2 "*" whitelist "* | *" whitelist "*" hy2 "* | *" hy2 "*" mobile "* | *" mobile "*" hy2 "*)
TAGS="$TAGS hy2_exit " ;;
esac
export SUB_LIST HY2_LIST HY2_MAIN 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". Same as bootSeeds() in web/engine.js.
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, ... Same algorithm as subPairs() in web/engine.js.
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
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=""
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_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
}
# variables for templates/proxies/*-hy2.each.yaml: hy2_vars <name>
# HY2_<NAME>_SERVER, _PORT, _PASSWORD required
# HY2_<NAME>_OBFS_PASSWORD salamander obfs (empty = none)
# HY2_<NAME>_SNI, _INSECURE=1 (skip-cert-verify), _UP, _DOWN ("50 mbps")
hy2_vars() {
_k=$(hy2_key "$1")
eval "HY2_SERVER=\${${_k}_SERVER} HY2_PORT=\${${_k}_PORT} _pw=\${${_k}_PASSWORD}
_ob=\${${_k}_OBFS_PASSWORD:-} HY2_SNI=\${${_k}_SNI:-} _in=\${${_k}_INSECURE:-0}
_up=\${${_k}_UP:-} _dn=\${${_k}_DOWN:-}"
HY2_NAME=$1
HY2_PASSWORD=$(yq "$_pw")
HY2_OBFS="" HY2_OBFS_PASSWORD=""
[ -n "$_ob" ] && HY2_OBFS=salamander HY2_OBFS_PASSWORD=$(yq "$_ob")
HY2_INSECURE=false
[ "$_in" = 1 ] && HY2_INSECURE=true
HY2_UP=$(yq "$_up") HY2_DOWN=$(yq "$_dn")
export HY2_NAME HY2_SERVER HY2_PORT HY2_PASSWORD HY2_OBFS HY2_OBFS_PASSWORD HY2_SNI \
HY2_INSECURE HY2_UP HY2_DOWN
}
render_file() {
awk -v tags="$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_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"
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
}$_part"
done
elif [ "$EACH" = 1 ] && [ "$_mod" = hy2 ]; then
for _n in $HY2; do
hy2_vars "$_n"
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
}$_part"
done
elif [ "$EACH" = 1 ]; then
i=0
for _pr in $SUB_PAIRS; do
if ! sub_off "$i" "${_pr%%=*}"; then
sub_vars "$i" "${_pr%%=*}" "${_pr#*=}"
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
}$_part"
fi
i=$((i + 1))
done
else
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
}$_part"
fi
done
[ -n "$_out" ] || return 0
[ -n "${2:-}" ] && printf "%s\n" "$2"
printf "%s\n" "$_out"
}
render() {
set_defaults
sub_pairs
boot_seeds
check_vars
compute_tags
export TARGET LOCATION GEOIP_URL GEOSITE_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 RU_IPS OVPN_CHECK_URL TS_CHECK_URL CSQTT_IFACE CSQTT_PROCESS
_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 (bmstu-otp.sh on puts it back), <name>.yaml - what mihomo
# reads: the list, or empty while the tunnel should be off (manual off, timer,
# schedule: bmstu-otp.sh want)
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 bmstu-otp.sh >/dev/null 2>&1; then
bmstu-otp.sh want 2>/dev/null || _on=0
elif [ -f "$NIKKI_DIR/bmstu.off" ]; then
_on=0
fi
if [ "$_on" = 0 ]; 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 this file
ovpn_routes_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 (FlClash): 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
}
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"
uci commit nikki
/etc/init.d/nikki restart
log "nikki now runs $1"
# OpenVPN of this profile: common.env, overridden by <name>.env
_ov=$(cat "$PROFILES_D/common.env" "$PROFILES_D/$1.env" 2>/dev/null | sed -n 's/^OPENVPN=//p' | tail -n 1 | tr -d "'\"")
[ "$_ov" = 1 ] && command -v bmstu-otp.sh >/dev/null 2>&1 || return 0
# off now (manual, schedule): up says so and does nothing
bmstu-otp.sh want || {
bmstu-otp.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
# (bmstu-otp.sh check) retries
sleep 5
bmstu-otp.sh up || log "warning: OpenVPN did not come up yet, the cron check retries within a minute"
return 0
}
# --- Tailscale login --------------------------------------------------------
TS_DIR="$NIKKI_DIR/run/tailscale"
CORE_LOG=/var/log/nikki/core.log
# mihomo API from nikki's mixin settings (same as bmstu-otp.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
# 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
}
# 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
case "$(uname -m)" in
aarch64) arch=arm64 ;;
x86_64) arch=amd64 ;;
armv7l) arch=armv7 ;;
mips) arch=mips-softfloat ;;
mipsel | mipsle) arch=mipsle-softfloat ;;
*)
log "warning: unknown arch $(uname -m), set the core manually"
return 1
;;
esac
url="$MIHOMO_BASE/mihomo-linux-$arch-$MIHOMO_VERSION.gz"
log "updating mihomo core ${cur:-none} -> $MIHOMO_VERSION"
# Streamed straight next to the binary: /tmp is RAM, and the unpacked core
# (~56 MB) plus the .gz do not fit on small routers. No .bak copy either (flash
# space); an older core comes back with MIHOMO_VERSION in /etc/nikki/kit.env + fix.
# A failed download keeps the current core: fix/update still start nikki.
bin=$(command -v mihomo || echo /usr/bin/mihomo)
new=$bin.new
rm -f "$new" "$bin.bak" /tmp/mihomo.gz /tmp/mihomo
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 ${bin%/*}: $(df -h "${bin%/*}" 2>/dev/null | awk 'NR==2 {print $4}')), keeping ${cur:-the current one}"
return 1
fi
CORE_PENDING=new
}
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)
mv "$bin.new" "$bin"
log "core: $(mihomo -v | head -n 1)"
;;
esac
CORE_PENDING=""
}
# 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/bmstu-otp.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
if grep -q "bmstu-otp.sh write" "$f"; then
log "init script already writes the OpenVPN provider"
else
sed -i "/$_anchor/a\\ [ -x /usr/bin/bmstu-otp.sh ] \\&\\& /usr/bin/bmstu-otp.sh write >/dev/null 2>\\&1" "$f"
log "added bmstu-otp.sh write to $f"
fi
}
# 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
}
install_files() {
for s in mihomo-kit.sh bmstu-otp.sh; do
chmod +x "$KIT_DIR/router/$s"
ln -sf "$KIT_DIR/router/$s" "/usr/bin/$s"
done
mkdir -p "$PROFILES_D"
chmod 700 "$PROFILES_D"
migrate_profiles
# 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 page "Services -> mihomo-kit" (luci/): rpcd plugin, ACL, menu, view.
# The view goes to view/mihomo-kit/v<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
_views=/www/luci-static/resources/view
_v=v$(md5sum < "$src/mihomo-kit.js" | cut -c1-8)
put "$src/mihomo-kit.js" "$_views/mihomo-kit/$_v.js" 644
for _f in "$_views/mihomo-kit.js" "$_views"/mihomo-kit/*.js; do
[ -f "$_f" ] && [ "$_f" != "$_views/mihomo-kit/$_v.js" ] && rm -f "$_f" && _changed=1
done
sed "s|\"path\": \"mihomo-kit\"|\"path\": \"mihomo-kit/$_v\"|" "$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 only on start; delayed so a job started from LuCI
# (kit update) gets to finish first
(sleep 5; /etc/init.d/rpcd restart) < /dev/null > /dev/null 2>&1 &
}
enable_otp_cron() {
grep -q "bmstu-otp.sh check" /etc/crontabs/root 2>/dev/null && return 0
echo '* * * * * /usr/bin/bmstu-otp.sh check' >> /etc/crontabs/root
/etc/init.d/cron restart
log "added bmstu-otp.sh check to cron"
}
cmd_install() {
opkg update
if [ ! -x /etc/init.d/nikki ]; then
wget -O - https://github.com/nikkinikki-org/OpenWrt-nikki/raw/refs/heads/main/feed.sh | ash
opkg install nikki luci-app-nikki
fi
for p in curl oath-toolkit; do
opkg list-installed | grep -q "^$p " || opkg install "$p"
done
# curl newer than libcurl -> "Error relocating ... symbol not found"
curl --version >/dev/null 2>&1 || opkg install --force-reinstall libcurl4 curl
install_files
cmd_fix
}
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
}
# --- 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)" y
yesno PUSH "Пуши (APNs, FCM) через группу PUSH" y
ask RU_IPS "Доп. IP через RU (CIDR через пробел)" ""
yesno OPENVPN "OpenVPN BMSTU" n
if [ "$OPENVPN" = 1 ]; then
while [ ! -f "$NIKKI_DIR/bmstu.ovpn" ]; do
ask _dummy "Положи .ovpn в $NIKKI_DIR/bmstu.ovpn (scp -O file.ovpn root@router:$NIKKI_DIR/bmstu.ovpn) и нажми Enter"
done
ask VPN_USERNAME " логин"
ask_secret VPN_PASSWORD " пароль (без OTP)"
ask_secret TOTP_SECRET " TOTP-секрет (base32 из QR)"
fi
yesno CSQTT "CSQTT (star-panel-csqtt, интерфейс csqtt0) первым в MAIN" 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|OPENVPN|TAILSCALE|TS_HOSTNAME|TS_DOMAINS|CSQTT'
VPN_KEYS='VPN_USERNAME|VPN_PASSWORD|TOTP_SECRET'
# 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 (+ bmstu.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>_*, check
# URLs) 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_]+|OVPN_CHECK_URL|TS_CHECK_URL|MOBILE"
_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:-1}"
echo "RU_IPS=$(q "$RU_IPS")"
echo "OPENVPN=$OPENVPN"
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"
echo "HY2=$(q "$HY2")"
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")"
echo "TOTP_SECRET=$(q "$TOTP_SECRET")"
other_keys "$NIKKI_DIR/bmstu.env" "$VPN_KEYS"
true
} > "$NIKKI_DIR/bmstu.env.tmp" && mv "$NIKKI_DIR/bmstu.env.tmp" "$NIKKI_DIR/bmstu.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, OPENVPN, CSQTT, VPN_* (empty secrets = keep), TAILSCALE, TS_*,
# FORM=1, OVPN_CHECK_URL, TS_CHECK_URL, HY2 + HY2_<NAME>_*.
# Validates, writes common.env/bmstu.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/bmstu.env" ] && . "$NIKKI_DIR/bmstu.env"
. "$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/bmstu.ovpn" ] || die "OpenVPN: нет $NIKKI_DIR/bmstu.ovpn"
[ -n "${VPN_USERNAME:-}" ] && [ -n "${VPN_PASSWORD:-}" ] && [ -n "${TOTP_SECRET:-}" ] ||
die "OpenVPN: нужны логин, пароль и TOTP-секрет"
fi
write_config
log "saved $PROFILES_D/common.env"
cmd_apply
}
# settings in profiles.d (+ bmstu.*) -> 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 -q "bmstu-otp.sh check" /etc/crontabs/root 2>/dev/null; then
sed -i '/bmstu-otp.sh check/d' /etc/crontabs/root
/etc/init.d/cron restart
log "removed bmstu-otp.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
}
# Settings bundle: one text file with profiles.d/*.env, bmstu.env, bmstu.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/bmstu.env" "$NIKKI_DIR/bmstu.ovpn"; 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)
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
profiles.d/*.env | bmstu.env | bmstu.ovpn) ;;
*) die "unexpected file in the export: $_f" ;;
esac
case "${_f#profiles.d/}" in */* | *[!A-Za-z0-9_.-]*) die "bad file name: $_f" ;; esac
done
_keep=""
if [ "${2:-}" = --keep-local ]; then
for _k in TS_HOSTNAME HWID_ID; do
_l=$(grep "^$_k=" "$PROFILES_D/common.env" 2>/dev/null | tail -n 1)
[ -n "$_l" ] && _keep="$_keep$_l
"
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/"
for _f in bmstu.env bmstu.ovpn; do
[ -f "$_tmp/$_f" ] && cp "$_tmp/$_f" "$NIKKI_DIR/$_f"
done
if [ -n "$_keep" ]; then
grep -vE '^(TS_HOSTNAME|HWID_ID)=' "$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
echo "OTP сейчас: $(bmstu-otp.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 " bmstu-otp.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
[ -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"*)
auto_log "up to date ($_new)"
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 ;;
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 ;;
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 "$@" ;;
*) sed -n '2,32p' "$SELF" >&2; exit 2 ;;
esac