mihomo-kit/router/mihomo-kit.sh
2026-10-09 17:39:40 +03:00

878 lines
28 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 (home, street, ...)
# /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 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 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_VERSION:=v1.19.32}"
: "${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 subscription
# 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:=home}"
: "${BOOT:=1}" "${TORRENT:=1}" "${OPENVPN:=0}" "${TAILSCALE:=0}" "${TS_EXIT:=0}"
: "${SUBS:=}" "${RU_IPS:=}"
: "${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_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}"
}
compute_tags() {
TAGS=" base sub $TARGET "
[ "$BOOT" = 1 ] && TAGS="$TAGS boot "
if [ "$TARGET" = router ]; then
TAGS="$TAGS $LOCATION "
[ "$TORRENT" = 1 ] && TAGS="$TAGS torrent "
[ "$OPENVPN" = 1 ] && TAGS="$TAGS openvpn "
if [ "$TAILSCALE" = 1 ]; then
TAGS="$TAGS tailscale "
[ "$TS_EXIT" = 1 ] && TAGS="$TAGS ts_exit "
fi
fi
SUB_LIST=""
for _p in $SUB_PAIRS; do
SUB_LIST="${SUB_LIST:+$SUB_LIST, }${_p%%=*}"
done
export SUB_LIST
}
# 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:-}}\""
}
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 home | street) ;; *) die "LOCATION must be home or street" ;; esac
if [ "$BOOT" = 1 ]; then
for v in BOOT_SERVER BOOT_UUID BOOT_SNI BOOT_PBK BOOT_SID; do
eval "[ -n \"\${$v}\" ]" || die "$v is empty (BOOT=1)"
done
fi
i=0
for _pr in $SUB_PAIRS; do
_id=${_pr%%=*}
[ "$(sub_get "$i" "$_id" PROXY)" = BOOT ] && [ "$BOOT" != 1 ] && die "subscription $_id: PROXY=BOOT but BOOT=0"
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
}
# 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 (default with BOOT=1) | DIRECT | 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)
[ -z "$_p" ] && [ "$BOOT" = 1 ] && _p=BOOT
[ "$_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
}
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 ]; then
i=0
for _pr in $SUB_PAIRS; do
sub_vars "$i" "${_pr%%=*}" "${_pr#*=}"
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
}$_part"
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
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
_first=1
for s in head proxies:proxies providers:proxy-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
}
cmd_build() {
[ -d "$PROFILES_D" ] || die "no $PROFILES_D (see profile.env.example)"
mkdir -p "$PROFILES_OUT"
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
}
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"
if grep -q "^OPENVPN=1" "$PROFILES_D/$1.env" "$PROFILES_D/common.env" 2>/dev/null &&
command -v bmstu-otp.sh >/dev/null 2>&1; then
sleep 5
bmstu-otp.sh refresh
fi
}
# --- 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"
return 1
fi
{
echo "Tailscale: войди по ссылке, потом в админке Tailscale — Disable key expiry для ноды"
echo " $url"
} >&2
}
# --- router setup -----------------------------------------------------------
core_update() {
cur=$(mihomo -v 2>/dev/null | awk '{print $3; exit}')
if [ "$cur" = "$MIHOMO_VERSION" ]; then
log "mihomo core is $cur"
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 ;;
*) die "unknown arch $(uname -m), set the core manually" ;;
esac
url="https://github.com/MetaCubeX/mihomo/releases/download/$MIHOMO_VERSION/mihomo-linux-$arch-$MIHOMO_VERSION.gz"
log "updating mihomo core ${cur:-none} -> $MIHOMO_VERSION"
curl -fL -o /tmp/mihomo.gz "$url" || die "download failed: $url"
gunzip -f /tmp/mihomo.gz && chmod +x /tmp/mihomo || die "unpack failed"
bin=$(command -v mihomo || echo /usr/bin/mihomo)
[ -f "$bin" ] && cp "$bin" "$bin.bak"
mv /tmp/mihomo "$bin"
log "core: $(mihomo -v | head -n 1)"
}
# Tailscale control over port 80 gets broken by the ISP: force 443.
patch_init() {
f=/etc/init.d/nikki
if grep -q TS_FORCE_NOISE_443 "$f"; then
log "init script already has TS_FORCE_NOISE_443"
elif grep -q "procd_append_param env SKIP_SYSTEM_IPV6_CHECK" "$f"; then
sed -i '/procd_append_param env SKIP_SYSTEM_IPV6_CHECK/a\ procd_append_param env TS_FORCE_NOISE_443=true' "$f"
log "added TS_FORCE_NOISE_443 to $f"
else
log "warning: anchor not found in $f, add 'procd_append_param env TS_FORCE_NOISE_443=true' by hand"
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
}
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"
install_luci
}
# LuCI page "Services -> mihomo-kit" (luci/): rpcd plugin, ACL, menu, view
install_luci() {
src=$KIT_DIR/luci
[ -d "$src" ] && [ -d /www/luci-static/resources ] || return 0
_changed=0
put() {
cmp -s "$1" "$2" && return 0
mkdir -p "$(dirname "$2")"
cp "$1" "$2"
_changed=1
}
put "$src/rpcd.sh" /usr/libexec/rpcd/mihomo-kit
chmod +x /usr/libexec/rpcd/mihomo-kit
put "$src/acl.json" /usr/share/rpcd/acl.d/luci-app-mihomo-kit.json
put "$src/menu.json" /usr/share/luci/menu.d/luci-app-mihomo-kit.json
put "$src/mihomo-kit.js" /www/luci-static/resources/view/mihomo-kit.js
[ "$_changed" = 1 ] || return 0
rm -rf /tmp/luci-indexcache* /tmp/luci-modulecache
log "LuCI page installed: Services -> mihomo-kit"
# 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() {
/etc/init.d/nikki stop 2>/dev/null
core_update
patch_init
fix_reserved
/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
}
# vless://uuid@host:port?...&sni=..&pbk=..&sid=..#name -> BOOT_* (empty on failure)
parse_vless() {
_l=${1#vless://}
_l=${_l%%#*}
BOOT_UUID=${_l%%@*}
_hp=${_l#*@}
_hp=${_hp%%\?*}
BOOT_SERVER=${_hp%:*}
BOOT_PORT=${_hp##*:}
_q="&${_l#*\?}&"
qv() { _v=${_q#*&$1=}; [ "$_v" = "$_q" ] && return; echo "${_v%%&*}"; }
BOOT_SNI=$(qv sni)
BOOT_PBK=$(qv pbk)
BOOT_SID=$(qv sid)
}
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 _vless "BOOT: vless:// ссылка seed-ноды (пусто = без BOOT)"
BOOT=0
if [ -n "$_vless" ]; then
parse_vless "$_vless"
[ -n "$BOOT_SERVER" ] && [ -n "$BOOT_PBK" ] || die "не разобрал vless-ссылку: нужны host, pbk, sid"
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/DIRECT)" BOOT
else
_p=DIRECT
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
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 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)|HWID_[A-Z_]+|BOOT|BOOT_[A-Z]+|TORRENT|RU_IPS|OPENVPN|TAILSCALE|TS_HOSTNAME|TS_DOMAINS'
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)
write_config() {
umask 077
_any_hwid=0
_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)
[ "$BOOT" = 1 ] || [ "$_p" != BOOT ] || _p=DIRECT
[ -n "$_p" ] && [ "$_p" != BOOT ] && echo "SUB_${_K}_PROXY=$(q "$_p")"
[ "$_hw" = 1 ] && echo "SUB_${_K}_HWID=1" && _any_hwid=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"
if [ "$BOOT" = 1 ]; then
for v in BOOT_SERVER BOOT_PORT BOOT_UUID BOOT_SNI BOOT_PBK BOOT_SID; do
eval "echo \"$v=\$(q \"\$$v\")\""
done
fi
echo "TORRENT=$TORRENT"
echo "RU_IPS=$(q "$RU_IPS")"
echo "OPENVPN=$OPENVPN"
echo "TAILSCALE=$TAILSCALE"
[ "$TAILSCALE" = 1 ] && echo "TS_HOSTNAME=$(q "$TS_HOSTNAME")" && echo "TS_DOMAINS=$(q "$TS_DOMAINS")"
[ -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_LINK, SUBS, SUB<i>_PROXY/HWID,
# HWID_*, TORRENT, RU_IPS, OPENVPN, VPN_* (empty secrets = keep), TAILSCALE, TS_*.
# 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
if [ -n "${BOOT_LINK:-}" ]; then
parse_vless "$BOOT_LINK"
[ -n "$BOOT_SERVER" ] && [ -n "$BOOT_PBK" ] || die "не разобрал vless-ссылку: нужны host, pbk, sid"
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_build
if [ "$OPENVPN" = 1 ]; 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=home
cmd_use "$cur"
[ "$TAILSCALE" = 1 ] && cmd_ts_login
true
}
# 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)" home
cmd_use "$_start"
grep -q "^TAILSCALE=1" "$PROFILES_D/common.env" && cmd_ts_login
{
echo
echo "Готово. Дальше:"
echo " mihomo-kit.sh use street|home переключить профиль"
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"
}
cmd_update() {
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
rm -rf "$tmp"
# the rest runs from the new script: this one is the old version
exec sh "$KIT_DIR/router/mihomo-kit.sh" post-update
}
cmd_post_update() {
install_files
cmd_build
cur=$(uci -q get nikki.config.profile)
log "kit updated; to apply: mihomo-kit.sh use $(basename "${cur#file:}" .yaml)"
}
case "${1:-}" in
render) shift; cmd_render "$@" ;;
build) shift; cmd_build "$@" ;;
use) shift; cmd_use "$@" ;;
setup) shift; cmd_setup "$@" ;;
configure) shift; cmd_configure "$@" ;;
sub-ids) cmd_sub_ids ;;
update) cmd_update ;;
post-update) cmd_post_update ;;
install) cmd_install ;;
fix) cmd_fix ;;
ts-login) shift; cmd_ts_login "$@" ;;
*) sed -n '2,26p' "$SELF" >&2; exit 2 ;;
esac