#!/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 (bmstu-otp.sh state: mode, schedule, tunnel from the core, # no traffic) + current OTP # ovpn_probe delay to OVPN_CHECK_URL through the tunnel (a request the site can log) # csqtt_status CSQTT state (mihomo-kit.sh csqtt state: csqtt status + group UPLINK) # 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 .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 csqtt "$(b test "$(envval CSQTT "$prof")" = 1)" json_add_boolean csqtt_installed "$(b command -v csqtt)" json_add_boolean lite "$(b test "$(envval LITE "$prof")" = 1)" pid=$(pidof mihomo) json_add_int mem_kb "$(awk '/^VmRSS:/ {print $2}' "/proc/${pid%% *}/status" 2>/dev/null)" 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/.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 : 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 # what decides the tunnel now and the next change (bmstu-otp.sh state); only # known keys with plain values get through to eval eval "$(bmstu-otp.sh state 2>/dev/null | sed -En -e 's/^(mode|want|tunnel|link|up_since|up_hm|up_day|retry_hm|retry_why|until|until_hm|until_day|after|why|next|next_to|next_hm|next_day|win|sched|sched_active|timer_max|sched_start|sched_end|sched_days|jitter)=([A-Za-z0-9:._-]*)$/st_\1=\2/p' \ -e "s/^err='([^'\`\$\\\\]*)'\$/st_err='\\1'/p")" for k in mode tunnel link up_hm up_day retry_hm retry_why err until_hm until_day after why next_to next_hm next_day win sched_start sched_end sched_days; do eval "json_add_string $k \"\${st_$k:-}\"" done for k in want up_since until next sched sched_active timer_max jitter; do eval "json_add_int $k \"\${st_$k:-0}\"" done json_add_string otp "$(bmstu-otp.sh otp 2>/dev/null)" json_add_int otp_left "$((30 - $(date +%s) % 30))" json_dump } m_csqtt_status() { json_init # only known keys with plain values get through to eval (as in m_ovpn_status) eval "$(mihomo-kit.sh csqtt state 2>/dev/null | sed -En -e 's/^(link|enabled|uplink|active|stage|captcha)=([A-Za-z0-9:._-]*)$/cq_\1=\2/p' \ -e "s/^(err|stats)='([^'\`\$\\\\]*)'\$/cq_\\1='\\2'/p")" for k in link uplink active stage err stats; do eval "json_add_string $k \"\${cq_$k:-}\"" done json_add_boolean enabled "${cq_enabled:-0}" json_add_int captcha "${cq_captcha:-0}" json_dump } # by hand only: the site sees the request (HEAD from a Go client) m_ovpn_probe() { json_init 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 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 ;; ovpn-for | ovpn-extend) case "$arg" in '' | *[!0-9]* | 0) reply_error "bad minutes" ;; esac set -- bmstu-otp.sh "${cmd#ovpn-}" "$arg" ;; ovpn-stop) set -- bmstu-otp.sh stop ;; ovpn-sched) # arg: "off" | "on" | "HH:MM HH:MM [DAYS]" (DAYS: digits 1..7); unquoted below to split case "$arg" in off | on | [0-9][0-9]:[0-9][0-9]\ [0-9][0-9]:[0-9][0-9]) ;; [0-9][0-9]:[0-9][0-9]\ [0-9][0-9]:[0-9][0-9]\ [1-7]*) case "${arg#* * }" in *[!1-7]*) reply_error "bad schedule days" ;; esac ;; *) reply_error "bad schedule" ;; esac set -- bmstu-otp.sh sched $arg ;; 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 ;; csqtt-on) set -- mihomo-kit.sh csqtt on ;; csqtt-off) set -- mihomo-kit.sh csqtt off ;; 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 # " "; keys SUB__*, else the old SUB_* 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_string foreign_ips "${FOREIGN_IPS:-}" json_add_string my_ips "${MY_IPS:-}" json_add_string ru_domains "${RU_DOMAINS:-}" json_add_string foreign_domains "${FOREIGN_DOMAINS:-}" json_add_string my_domains "${MY_DOMAINS:-}" json_add_string local_hosts "${LOCAL_HOSTS:-}" # own servers as links: one per line in the form set -f json_add_string my_links "$(printf '%s\n' ${MY_LINKS:-})" set +f json_add_boolean openvpn "${OPENVPN:-0}" json_add_boolean csqtt "${CSQTT:-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_boolean lite "${LITE:-0}" json_add_string lite_gomemlimit "${LITE_GOMEMLIMIT:-}" 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, # foreign_ips, my_ips, ru_domains, foreign_domains, my_domains, local_hosts, my_links (one per line), # openvpn, csqtt, ovpn (file text, optional), vpn_username, vpn_password, totp_secret, # tailscale, ts_hostname, ts_domains, lite, lite_gomemlimit, 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 foreign_ips my_ips \ ru_domains foreign_domains my_domains local_hosts my_links openvpn csqtt ovpn \ vpn_username vpn_password totp_secret tailscale ts_hostname ts_domains ovpn_check_url ts_check_url mobile \ lite lite_gomemlimit; 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 "FOREIGN_IPS=$(q "$foreign_ips")" echo "MY_IPS=$(q "$my_ips")" echo "RU_DOMAINS=$(q "$ru_domains")" echo "FOREIGN_DOMAINS=$(q "$foreign_domains")" echo "MY_DOMAINS=$(q "$my_domains")" echo "LOCAL_HOSTS=$(q "$local_hosts")" # one link per line; a space is never part of a link (a name with spaces after # -> %20) echo "MY_LINKS=$(q "$(printf '%s\n' "$my_links" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//; s/[[:space:]]/%20/g' | grep . | tr '\n' ' ' | sed 's/ $//')")" echo "OPENVPN=$(q "${openvpn:-0}")" echo "CSQTT=$(q "${csqtt:-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}")" echo "LITE=$(q "${lite:-0}")" echo "LITE_GOMEMLIMIT=$(q "$lite_gomemlimit")" 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":{},"ovpn_probe":{},"csqtt_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 ;; ovpn_probe) m_ovpn_probe ;; csqtt_status) m_csqtt_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