mihomo-kit/luci/rpcd.sh
2026-10-12 18:53:39 +03:00

406 lines
14 KiB
Bash

#!/bin/sh
# rpcd plugin "mihomo-kit" for the LuCI page (installed as /usr/libexec/rpcd/mihomo-kit).
#
# status profile, nikki running, which features are on, kit version,
# mihomo API port/secret (dashboard link)
# ovpn_status OpenVPN state (up/down/off, delay to OVPN_CHECK_URL) + current OTP
# run start a whitelisted command as the background job
# job the job's command, state, exit code and output
# update_check latest kit commit on the git server vs the installed one
# ts_check Tailscale delay test to TS_CHECK_URL through the mihomo API
# export all settings as one text file (mihomo-kit.sh export)
# import {data, keep_local}: replace the settings with an export, as the job
# config_get settings for the form (secrets: only whether they are set)
# config_set save the form (via "mihomo-kit.sh configure") as the job
#
# rpcd kills calls after ~30 s; use/update/ts-login take longer, hence the job.
. /usr/share/libubox/jshn.sh
export PATH=/usr/sbin:/usr/bin:/sbin:/bin
# rpcd runs with umask 077; jobs (kit update) install web files that must stay readable
umask 022
NIKKI_DIR=/etc/nikki
PROFILES_D=$NIKKI_DIR/profiles.d
JOB=/tmp/mihomo-kit-job
# 1 if the command succeeds, else 0 (for json_add_boolean)
b() { "$@" >/dev/null 2>&1 && echo 1 || echo 0; }
# envval VAR profile -> value from common.env, overridden by <profile>.env
envval() {
cat "$PROFILES_D/common.env" "$PROFILES_D/$2.env" 2>/dev/null |
sed -n "s/^$1=//p" | tail -n 1 | tr -d "'\""
}
q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
job_running() { [ -f "$JOB/pid" ] && kill -0 "$(cat "$JOB/pid")" 2>/dev/null; }
# mihomo API base URL from nikki's mixin settings (as in bmstu-otp.sh)
api_url() {
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
echo "http://$host:$port"
}
reply_error() {
json_init
json_add_string error "$1"
json_dump
exit 0
}
m_status() {
prof=$(uci -q get nikki.config.profile)
prof=${prof#file:}
prof=${prof%.yaml}
json_init
json_add_string profile "$prof"
json_add_boolean running "$(b pidof mihomo)"
json_add_boolean configured "$(b test -f "$PROFILES_D/common.env")"
json_add_array profiles
for f in "$NIKKI_DIR"/profiles/*.yaml; do
[ -f "$f" ] || continue
n=${f##*/}
json_add_string "" "${n%.yaml}"
done
json_close_array
json_add_boolean openvpn "$(b test "$(envval OPENVPN "$prof")" = 1)"
json_add_boolean tailscale "$(b test "$(envval TAILSCALE "$prof")" = 1)"
json_add_boolean ts_logged_in "$(b grep -q _current-profile "$NIKKI_DIR/run/tailscale/tailscaled.state")"
json_add_string kit_version "$(cat "$NIKKI_DIR/kit/VERSION" 2>/dev/null)"
# installed core vs the one the kit pins (MIHOMO_VERSION default in mihomo-kit.sh)
json_add_string core_version "$(mihomo -v 2>/dev/null | awk '{print $3; exit}')"
# choice, wanted, ok, stock/official/kit versions, free_kb, need_kb
json_add_object core
mihomo-kit.sh core-info > /tmp/mihomo-kit-core.$$ 2>/dev/null
while read -r k v; do
json_add_string "$k" "$v"
done < /tmp/mihomo-kit-core.$$
rm -f /tmp/mihomo-kit-core.$$
json_close_object
json_add_boolean auto_update "$(b grep -q 'mihomo-kit.sh auto-update' /etc/crontabs/root)"
# phone config (MOBILE=1): /mihomo-kit/<token>.yaml served by uhttpd
mob=$(ls /www/mihomo-kit/*.yaml 2>/dev/null | head -n 1)
json_add_string mobile_path "${mob:+/mihomo-kit/${mob##*/}}"
json_add_string auto_update_last "$(tail -n 1 "$NIKKI_DIR/kit/auto-update.log" 2>/dev/null)"
l=$(uci -q get nikki.mixin.api_listen)
port=${l##*:}
case "$port" in '' | *[!0-9]*) port=9090 ;; esac
json_add_int api_port "$port"
json_add_string api_secret "$(uci -q get nikki.mixin.api_secret)"
json_dump
}
# delay_check <group> <VAR> <default url>: delay test of the group to the
# check URL (from common.env + profile env) through the mihomo API -> json fields
delay_check() {
prof=$(uci -q get nikki.config.profile)
prof=${prof#file:}
prof=${prof%.yaml}
url=$(envval "$2" "$prof")
# defaults: the same as set_defaults in mihomo-kit.sh
[ -n "$url" ] || url=$3
json_add_string url "$url"
sec=$(uci -q get nikki.mixin.api_secret)
res=$(curl -sS -m 12 ${sec:+-H "Authorization: Bearer $sec"} -G \
--data-urlencode "url=$url" --data-urlencode timeout=8000 \
"$(api_url)/proxies/$1/delay" 2>&1)
delay=$(jsonfilter -s "$res" -e '@.delay' 2>/dev/null)
if [ -n "$delay" ]; then
json_add_string state up
json_add_int delay "$delay"
else
json_add_string state down
json_add_string message "$(jsonfilter -s "$res" -e '@.message' 2>/dev/null || echo "$res")"
fi
}
m_ovpn_status() {
json_init
if [ -f "$NIKKI_DIR/bmstu.off" ]; then
json_add_string state off
else
prof=$(uci -q get nikki.config.profile)
prof=${prof#file:}
group=$(envval OVPN_GROUP "${prof%.yaml}")
delay_check "${group:-BMSTU}" OVPN_CHECK_URL https://eu.bmstu.ru
fi
json_add_string otp "$(bmstu-otp.sh otp 2>/dev/null)"
json_add_int otp_left "$((30 - $(date +%s) % 30))"
json_dump
}
m_run() {
input=$(cat)
cmd=$(jsonfilter -s "$input" -e '@.cmd' 2>/dev/null)
arg=$(jsonfilter -s "$input" -e '@.arg' 2>/dev/null)
case "$cmd" in
ovpn-on) set -- bmstu-otp.sh on ;;
ovpn-off) set -- bmstu-otp.sh off ;;
ovpn-refresh) set -- bmstu-otp.sh refresh ;;
use)
case "$arg" in '' | *[!A-Za-z0-9_-]*) reply_error "bad profile name" ;; esac
[ -f "$NIKKI_DIR/profiles/$arg.yaml" ] || reply_error "no profile $arg"
set -- mihomo-kit.sh use "$arg"
;;
ts-login) set -- mihomo-kit.sh ts-login ;;
ts-relogin) set -- mihomo-kit.sh ts-login -f ;;
build | update | fix) set -- mihomo-kit.sh "$cmd" ;;
autoupdate-on) set -- mihomo-kit.sh auto-update on ;;
autoupdate-off) set -- mihomo-kit.sh auto-update off ;;
mobile-new) set -- mihomo-kit.sh mobile new ;;
core)
case "$arg" in stock | official | kit) ;; *) reply_error "bad core choice" ;; esac
set -- mihomo-kit.sh core "$arg"
;;
*) reply_error "unknown command: $cmd" ;;
esac
start_job "$@"
}
# start_job cmd args...: run it in the background, reply at once
start_job() {
job_running && reply_error "busy: $(cat "$JOB/cmd")"
rm -rf "$JOB"
mkdir -p "$JOB"
echo "$*" > "$JOB/cmd"
# detached from rpcd: all fds redirected, so the call returns at once
(
"$@"
echo $? > "$JOB/rc"
) < /dev/null > "$JOB/log" 2>&1 &
echo $! > "$JOB/pid"
json_init
json_add_string started "$*"
json_dump
}
m_config_get() {
[ -f "$PROFILES_D/common.env" ] && . "$PROFILES_D/common.env"
[ -f "$NIKKI_DIR/bmstu.env" ] && . "$NIKKI_DIR/bmstu.env"
[ -f /etc/openwrt_release ] && . /etc/openwrt_release
json_init
json_add_boolean configured "$(b test -f "$PROFILES_D/common.env")"
# BOOT_LINKS one per line; the old single BOOT_* as one link
links=
if [ "${BOOT:-0}" = 1 ]; then
if [ -n "${BOOT_LINKS:-}" ]; then
links=$(printf '%s\n' $BOOT_LINKS)
elif [ -n "${BOOT_SERVER:-}" ]; then
links="vless://$BOOT_UUID@$BOOT_SERVER:${BOOT_PORT:-443}?security=reality&sni=$BOOT_SNI&pbk=$BOOT_PBK&sid=$BOOT_SID"
fi
fi
json_add_string boot_links "$links"
json_add_array subs
i=0
# "<id> <SUBS word>"; keys SUB_<ID>_*, else the old SUB<index>_*
SUBS=${SUBS:-} mihomo-kit.sh sub-ids > /tmp/mihomo-kit-ids.$$
while read -r id w; do
K=$(echo "$id" | tr 'a-z' 'A-Z')
eval "p=\${SUB_${K}_PROXY:-\${SUB${i}_PROXY:-}} h=\${SUB_${K}_HWID:-\${SUB${i}_HWID:-0}}
off=\${SUB_${K}_DISABLED:-\${SUB${i}_DISABLED:-0}}"
[ -n "$p" ] || p=BOOT-AUTO
json_add_object ""
json_add_string id "$id"
json_add_string url "$w"
json_add_string via "$p"
json_add_boolean hwid "$h"
json_add_boolean enabled "$([ "$off" = 1 ] && echo 0 || echo 1)"
json_close_object
i=$((i + 1))
done < /tmp/mihomo-kit-ids.$$
rm -f /tmp/mihomo-kit-ids.$$
json_close_array
# HWID defaults: the same as the terminal wizard suggests
json_add_string hwid_ua "${HWID_UA:-v2rayN/9.99}"
json_add_string hwid_os "${HWID_OS:-OpenWrt}"
json_add_string hwid_os_ver "${HWID_OS_VER:-${DISTRIB_RELEASE:-}}"
json_add_string hwid_model "${HWID_MODEL:-$(cat /tmp/sysinfo/model 2>/dev/null)}"
json_add_string hwid_id "${HWID_ID:-$(md5sum < /sys/class/net/br-lan/address 2>/dev/null | cut -c1-16)}"
json_add_boolean torrent "${TORRENT:-1}"
json_add_boolean push "${PUSH:-1}"
json_add_string ru_ips "${RU_IPS:-}"
json_add_boolean openvpn "${OPENVPN:-0}"
json_add_boolean ovpn_file "$(b test -f "$NIKKI_DIR/bmstu.ovpn")"
json_add_string vpn_username "${VPN_USERNAME:-}"
json_add_boolean has_vpn_password "$(b test -n "${VPN_PASSWORD:-}")"
json_add_boolean has_totp "$(b test -n "${TOTP_SECRET:-}")"
json_add_boolean tailscale "${TAILSCALE:-0}"
json_add_string ts_hostname "${TS_HOSTNAME:-$(uci -q get 'system.@system[0].hostname' | tr 'A-Z' 'a-z')-mihomo}"
json_add_string ts_domains "${TS_DOMAINS:-}"
json_add_string ovpn_check_url "${OVPN_CHECK_URL:-https://eu.bmstu.ru}"
json_add_string ts_check_url "${TS_CHECK_URL:-http://100.69.216.50:8080}"
json_add_boolean mobile "${MOBILE:-0}"
json_add_array hy2
for n in ${HY2:-}; do
k=HY2_$(echo "$n" | tr 'a-z-' 'A-Z_')
json_add_object ""
json_add_string name "$n"
for v in server port password obfs_password sni insecure up down; do
eval "val=\${${k}_$(echo "$v" | tr 'a-z' 'A-Z'):-}"
json_add_string "$v" "$val"
done
json_close_object
done
json_close_array
json_dump
}
# {"data": {boot_links (one per line), subs: [{url, via, hwid}], hwid_*, torrent, push, ru_ips,
# openvpn, ovpn (file text, optional), vpn_username, vpn_password, totp_secret,
# tailscale, ts_hostname, ts_domains, hy2: [{name, server, port, password,
# obfs_password, sni, insecure, up, down}]}}; empty OpenVPN secrets keep the saved ones
m_config_set() {
json_load "$(cat)" || reply_error "bad request"
json_select data || reply_error "no data"
job_running && reply_error "busy: $(cat "$JOB/cmd")"
for v in boot_links hwid_ua hwid_os hwid_os_ver hwid_model hwid_id torrent push ru_ips openvpn ovpn \
vpn_username vpn_password totp_secret tailscale ts_hostname ts_domains ovpn_check_url ts_check_url mobile; do
json_get_var "$v" "$v" ""
done
if [ -n "$ovpn" ]; then
umask 077
printf '%s\n' "$ovpn" > "$NIKKI_DIR/bmstu.ovpn.tmp" && mv "$NIKKI_DIR/bmstu.ovpn.tmp" "$NIKKI_DIR/bmstu.ovpn"
fi
umask 077
env=$(mktemp /tmp/mihomo-kit-form.XXXXXX) || reply_error "mktemp failed"
{
echo "BOOT_LINKS=$(q "$(echo $boot_links)")"
subs= i=0
if json_select subs; then
json_get_keys keys
for k in $keys; do
url= via= hwid= enabled=
json_select "$k"
json_get_vars url via hwid enabled
json_select ..
url=$(printf '%s' "$url" | tr -d ' \t\r\n')
[ -n "$url" ] || continue
subs="${subs:+$subs }$url"
echo "SUB${i}_PROXY=$(q "$via")"
echo "SUB${i}_HWID=$(q "${hwid:-0}")"
[ "$enabled" = 0 ] && echo "SUB${i}_DISABLED=1"
i=$((i + 1))
done
json_select ..
fi
echo "SUBS=$(q "$subs")"
echo "HWID_UA=$(q "$hwid_ua")"
echo "HWID_OS=$(q "$hwid_os")"
echo "HWID_OS_VER=$(q "$hwid_os_ver")"
echo "HWID_MODEL=$(q "$hwid_model")"
echo "HWID_ID=$(q "$hwid_id")"
echo "TORRENT=$(q "${torrent:-0}")"
echo "PUSH=$(q "${push:-0}")"
echo "RU_IPS=$(q "$ru_ips")"
echo "OPENVPN=$(q "${openvpn:-0}")"
echo "VPN_USERNAME=$(q "$vpn_username")"
[ -n "$vpn_password" ] && echo "VPN_PASSWORD=$(q "$vpn_password")"
[ -n "$totp_secret" ] && echo "TOTP_SECRET=$(q "$totp_secret")"
echo "TAILSCALE=$(q "${tailscale:-0}")"
echo "TS_HOSTNAME=$(q "$ts_hostname")"
echo "TS_DOMAINS=$(q "$ts_domains")"
echo "FORM=1"
echo "OVPN_CHECK_URL=$(q "$ovpn_check_url")"
echo "TS_CHECK_URL=$(q "$ts_check_url")"
echo "MOBILE=$(q "${mobile:-0}")"
hy2=
if json_select hy2; then
json_get_keys keys
for k in $keys; do
json_select "$k"
json_get_var name name ""
name=$(printf '%s' "$name" | tr -d ' \t\r\n')
if [ -n "$name" ]; then
hy2="${hy2:+$hy2 }$name"
K=HY2_$(echo "$name" | tr 'a-z-' 'A-Z_')
for v in server port password obfs_password sni insecure up down; do
json_get_var val "$v" ""
echo "${K}_$(echo "$v" | tr 'a-z' 'A-Z')=$(q "$val")"
done
fi
json_select ..
done
json_select ..
fi
echo "HY2=$(q "$hy2")"
} > "$env"
umask 022
start_job mihomo-kit.sh configure "$env"
}
m_ts_check() {
json_init
delay_check TAILSCALE TS_CHECK_URL http://100.69.216.50:8080
json_dump
}
m_update_check() {
out=$(mihomo-kit.sh check-update 2>&1) || reply_error "$(echo "$out" | tail -n 1)"
json_init
echo "$out" > /tmp/mihomo-kit-upd.$$
while read -r k v; do
json_add_string "$k" "$v"
done < /tmp/mihomo-kit-upd.$$
rm -f /tmp/mihomo-kit-upd.$$
json_dump
}
m_export() {
json_init
json_add_string name "mihomo-kit-$(uci -q get 'system.@system[0].hostname')-$(date '+%Y%m%d').kit"
json_add_string data "$(mihomo-kit.sh export 2>/dev/null)"
json_dump
}
m_import() {
json_load "$(cat)" || reply_error "bad request"
json_get_var data data ""
json_get_var keep keep_local 0
job_running && reply_error "busy: $(cat "$JOB/cmd")"
umask 077
f=$(mktemp /tmp/mihomo-kit-import.XXXXXX) || reply_error "mktemp failed"
printf '%s\n' "$data" > "$f"
umask 022
head -n 1 "$f" | grep -q '^# mihomo-kit export v1' || { rm -f "$f"; reply_error "это не файл экспорта mihomo-kit"; }
if [ "$keep" = 1 ]; then
start_job mihomo-kit.sh import "$f" --keep-local
else
start_job mihomo-kit.sh import "$f"
fi
}
m_job() {
json_init
json_add_string cmd "$(cat "$JOB/cmd" 2>/dev/null)"
json_add_boolean running "$(b job_running)"
[ -f "$JOB/rc" ] && json_add_int rc "$(cat "$JOB/rc")"
json_add_string log "$(tail -c 20000 "$JOB/log" 2>/dev/null)"
json_dump
}
case "$1" in
list)
echo '{"status":{},"ovpn_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{},"export":{},"import":{"data":"str","keep_local":true}}'
;;
call)
case "$2" in
status) m_status ;;
ovpn_status) m_ovpn_status ;;
job) m_job ;;
run) m_run ;;
config_get) m_config_get ;;
config_set) m_config_set ;;
update_check) m_update_check ;;
ts_check) m_ts_check ;;
export) m_export ;;
import) m_import ;;
*) reply_error "unknown method" ;;
esac
;;
esac