diff --git a/README.md b/README.md index c848c65..0c2a635 100644 --- a/README.md +++ b/README.md @@ -64,9 +64,20 @@ mihomo-kit.sh use foreign # за рубежом: российское чер bmstu-otp.sh off # OpenVPN выключить: освободить сессию для другого устройства bmstu-otp.sh on # включить обратно +bmstu-otp.sh for 60 # поднять на 60 минут, потом само выключится +bmstu-otp.sh sched 09:00 17:00 # работать только в эти часы (МСК); sched off — отключить bmstu-otp.sh status ``` +Эти же кнопки и поле расписания есть на странице LuCI (Службы → mihomo-kit). + +Приоритеты: ручное «Выключить» держится поверх расписания, пока не нажмёшь «Включить». +Таймер (`for`) и расписание поднимают туннель, но ручной офф их перебивает. По истечении +таймера управление возвращается расписанию. Вне рабочих часов поднять туннель можно +таймером — обычное «Включить» расписание тут же погасит. Время — локальное на роутере (МСК); +у границ окна добавляется разброс до ±10 минут, свой на каждый день, чтобы включение и +выключение не приходились каждый раз на одну и ту же секунду. + На сервере BMSTU одна сессия на пользователя. `off` закрывает туннель в mihomo и не даёт cron поднять его снова, и убирает его подсети (`OVPN_ROUTES`) из маршрутизации: они лежат в rule-provider `bmstu-routes`, который `off` очищает, а `on` возвращает, без перезапуска nikki. @@ -251,7 +262,7 @@ control-сервер и DERP идут по TCP через `dialer-proxy`. На - `stock` — ядро из пакета nikki/прошивки (`/usr/libexec/mihomo`), ничего не качается, место во флеше освобождается; - `official` — официальный релиз MetaCubeX `CORE_OFFICIAL`; -- `kit` (по умолчанию) — своя сборка `CORE_KIT` с правкой для Tailscale. +- `kit` (по умолчанию) — своя сборка `CORE_KIT`: официальное ядро с правками kit (см. «Ядро kit»). Распакованному ядру нужно ~56 МБ во флеше: на роутерах с маленьким `/overlay` остаётся `stock`. Версии `CORE_OFFICIAL`/`CORE_KIT` задаются в `router/mihomo-kit.sh` — роутеры с diff --git a/luci/mihomo-kit.js b/luci/mihomo-kit.js index 25ebf9e..767d5c7 100644 --- a/luci/mihomo-kit.js +++ b/luci/mihomo-kit.js @@ -253,7 +253,7 @@ return view.extend({ E('a', { 'href': dash, 'target': '_blank', 'rel': 'noreferrer' }, 'открыть дашборд') ] : E('strong', 'остановлен')), row('Ядро mihomo', [ st.core_version || 'не найдено' ] - .concat(/-ts\d+$/.test(st.core_version || '') ? [ ' — сборка kit с правкой для Tailscale' ] : []) + .concat(/-ts\d+$/.test(st.core_version || '') ? [ ' — сборка kit: официальное ядро с правками kit' ] : []) .concat(st.core && st.core.ok == '0' ? [ ' — ', E('strong', { 'style': 'color:#c00' }, 'выбрано ' + (st.core.wanted == 'stock' ? 'ядро из прошивки' : st.core.wanted)), @@ -268,6 +268,11 @@ return view.extend({ if (st.openvpn) { var ovpnState = E('span', '—'); var otp = E('span', '—'); + var schedInfo = E('span', '—'); + var schedOn = E('input', { 'type': 'checkbox' }); + var schedStart = E('input', { 'type': 'time', 'value': '09:00' }); + var schedEnd = E('input', { 'type': 'time', 'value': '17:00' }); + var schedFilled = false; var ovpnCheck = function() { dom.content(ovpnState, E('em', 'проверяю…')); return callOvpnStatus().then(function(o) { @@ -279,6 +284,15 @@ return view.extend({ if (o.url) ovpnState.appendChild(E('span', { 'class': 'cbi-value-description' }, [ ' — ', o.url ])); dom.content(otp, o.otp ? o.otp + ' (ещё ' + o.otp_left + ' с)' : '—'); + var bits = [ o.sched ? 'расписание ' + o.sched_start + '–' + o.sched_end + ' MSK' : 'расписание выключено' ]; + if (o.until) bits.push('таймер ещё ' + Math.max(1, Math.round((o.until * 1000 - Date.now()) / 60000)) + ' мин'); + dom.content(schedInfo, bits.join(', ')); + if (!schedFilled) { + schedOn.checked = !!o.sched; + if (o.sched_start) schedStart.value = o.sched_start; + if (o.sched_end) schedEnd.value = o.sched_end; + schedFilled = true; + } }).catch(function(e) { dom.content(ovpnState, String(e)); }); }; ovpnCheck(); @@ -286,14 +300,21 @@ return view.extend({ E('table', { 'class': 'table' }, [ row('Состояние', [ ovpnState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, ovpnCheck) }, 'Проверить') ]), - row('OTP сейчас', otp) + row('OTP сейчас', otp), + row('Режим', schedInfo) ]), E('div', { 'class': 'cbi-page-actions' }, [ this.button('Включить', 'positive', 'ovpn-on'), ' ', + this.button('Включить на 1 ч', 'action', 'ovpn-for', '60'), ' ', this.button('Выключить', 'negative', 'ovpn-off', null, 'Закрыть туннель? Сессия на сервере освободится в течение ~5 минут.'), ' ', this.button('Переподключить', 'action', 'ovpn-refresh') - ]) + ]), + field('Расписание (MSK)', [ schedOn, ' ', schedStart, ' – ', schedEnd, ' ', + this.button('Сохранить', 'action', 'ovpn-sched', function() { + return schedOn.checked ? schedStart.value + ' ' + schedEnd.value : 'off'; + }) ], + 'Туннель работает только в эти часы (±10 мин разброс). Ручное «Выключить» держится поверх расписания до «Включить». «на 1 ч» поднимает вне окна.') ])); } @@ -714,7 +735,7 @@ return view.extend({ var opts = [ [ 'stock', 'Из прошивки' + (c.stock ? ' (' + c.stock + ')' : ' (нет)'), !c.stock ], [ 'official', 'Официальное ' + (c.official || ''), false ], - [ 'kit', 'kit ' + (c.kit || '') + ' (правка для Tailscale)', false ] + [ 'kit', 'Сборка kit ' + (c.kit || '') + ' (официальное + правки kit)', false ] ]; var sel = E('select', { 'class': 'cbi-input-select' }, opts.map(function(o) { var opt = E('option', { 'value': o[0] }, o[1]); diff --git a/luci/rpcd.sh b/luci/rpcd.sh index bf66a7b..3c79473 100644 --- a/luci/rpcd.sh +++ b/luci/rpcd.sh @@ -33,6 +33,11 @@ envval() { sed -n "s/^$1=//p" | tail -n 1 | tr -d "'\"" } +# bmstuval VAR -> value from bmstu.env (OpenVPN schedule lives there) +bmstuval() { + sed -n "s/^$1=//p" "$NIKKI_DIR/bmstu.env" 2>/dev/null | 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; } @@ -131,6 +136,12 @@ m_ovpn_status() { fi json_add_string otp "$(bmstu-otp.sh otp 2>/dev/null)" json_add_int otp_left "$((30 - $(date +%s) % 30))" + json_add_boolean sched "$(b test "$(bmstuval OVPN_SCHED)" = 1)" + json_add_string sched_start "$(bmstuval OVPN_SCHED_START)" + json_add_string sched_end "$(bmstuval OVPN_SCHED_END)" + _until=$(cat "$NIKKI_DIR/bmstu.until" 2>/dev/null) + case "$_until" in '' | *[!0-9]*) _until=0 ;; esac + [ "$_until" -gt "$(date +%s)" ] && json_add_int until "$_until" || json_add_int until 0 json_dump } @@ -142,6 +153,18 @@ m_run() { ovpn-on) set -- bmstu-otp.sh on ;; ovpn-off) set -- bmstu-otp.sh off ;; ovpn-refresh) set -- bmstu-otp.sh refresh ;; + ovpn-for) + case "$arg" in '' | *[!0-9]* | 0) reply_error "bad minutes" ;; esac + set -- bmstu-otp.sh for "$arg" + ;; + ovpn-sched) + # arg: "off" | "on" | "HH:MM HH:MM"; unquoted below to split the two times + case "$arg" in + off | on | [0-9][0-9]:[0-9][0-9]\ [0-9][0-9]:[0-9][0-9]) ;; + *) 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" diff --git a/router/bmstu-otp.sh b/router/bmstu-otp.sh index edc195c..97368e0 100755 --- a/router/bmstu-otp.sh +++ b/router/bmstu-otp.sh @@ -16,10 +16,13 @@ # bmstu-otp.sh refresh regenerate provider with fresh OTP, reload, warm up # bmstu-otp.sh up refresh unless the tunnel already answers # bmstu-otp.sh write only regenerate the provider (nikki init, before mihomo starts) -# bmstu-otp.sh check warm-up test; refresh only if two probes fail (cron) -# bmstu-otp.sh off close the tunnel and keep it closed (BMSTU traffic goes without it); -# frees the single server session for another client (the kit core -# sends EXIT; other cores leave it until the server's ping-restart, ~5 min) +# bmstu-otp.sh check reconcile to the desired state (schedule/timer/manual); the +# two-probe test refreshes a dead tunnel (cron, once a minute) +# bmstu-otp.sh for N bring the tunnel up for N minutes, then let the schedule resume +# bmstu-otp.sh sched ... off | on | HH:MM HH:MM: work-hours schedule (MSK), persisted +# bmstu-otp.sh off close the tunnel and keep it closed (sticky, wins over the schedule; +# BMSTU traffic goes without it); frees the single server session (the +# kit core sends EXIT; other cores leave it until ping-restart, ~5 min) # bmstu-otp.sh on allow the tunnel again and bring it up # bmstu-otp.sh status on/off and whether the tunnel answers # bmstu-otp.sh debug show the real handshake error in the nikki log @@ -46,8 +49,16 @@ api_from_uci() { } : "${API:=$(api_from_uci)}" : "${API_SECRET:=$(uci_get nikki.mixin.api_secret)}" -# while this file exists the tunnel stays off (bmstu-otp.sh off/on) +# while this file exists the tunnel stays off (bmstu-otp.sh off/on); it is the +# sticky manual off and wins over the schedule : "${OFF_FLAG:=/etc/nikki/bmstu.off}" +# timer (bmstu-otp.sh for N): holds an epoch; the tunnel stays up until then, +# overriding the schedule, then this file is removed and the schedule resumes +: "${UNTIL_FLAG:=/etc/nikki/bmstu.until}" +# schedule: with OVPN_SCHED=1 the tunnel is up only inside [START,END] local time +# (the router is MSK). A deterministic per-day jitter of up to OVPN_SCHED_JITTER +# minutes is added to each edge so the on/off moments are not identical every day. +: "${OVPN_SCHED:=0}" "${OVPN_SCHED_START:=09:00}" "${OVPN_SCHED_END:=17:00}" "${OVPN_SCHED_JITTER:=10}" : "${CHECK_URL:=https://www.bmstu.ru}" # ms, must exceed HANDSHAKE_TIMEOUT (max 32767) : "${CHECK_TIMEOUT:=25000}" @@ -289,6 +300,111 @@ refresh() { fi } +# --- schedule / timer ------------------------------------------------------- + +# "HH:MM" -> minutes since midnight on stdout; non-zero on a malformed value +hhmm_to_min() { + case "$1" in + [0-9][0-9]:[0-9][0-9]) : ;; + *) return 1 ;; + esac + _h=${1%:*} _m=${1#*:} + _h=$((10#$_h)) _m=$((10#$_m)) + [ "$_h" -le 23 ] && [ "$_m" -le 59 ] || return 1 + echo $((_h * 60 + _m)) +} + +# deterministic offset in [-JITTER, +JITTER] minutes for a seed (date + edge), +# so each edge shifts by a fixed amount for the whole day and differs day to day +jitter_min() { + [ "${OVPN_SCHED_JITTER:-0}" -gt 0 ] 2>/dev/null || { echo 0; return; } + _span=$((OVPN_SCHED_JITTER * 2 + 1)) + _hex=$(printf '%s' "$1" | md5sum 2>/dev/null | cut -c1-6) + [ -n "$_hex" ] || { echo 0; return; } + echo $((0x$_hex % _span - OVPN_SCHED_JITTER)) +} + +# true when now is inside the (jittered) schedule window; handles a window that +# wraps past midnight (END <= START). NOW_MIN/SCHED_DAY override the clock in tests. +in_window() { + _now=${NOW_MIN:-$((10#$(date +%H) * 60 + 10#$(date +%M)))} + _day=${SCHED_DAY:-$(date +%F)} + _s=$(hhmm_to_min "$OVPN_SCHED_START") || { log "bad OVPN_SCHED_START=$OVPN_SCHED_START"; return 0; } + _e=$(hhmm_to_min "$OVPN_SCHED_END") || { log "bad OVPN_SCHED_END=$OVPN_SCHED_END"; return 0; } + _s=$((_s + $(jitter_min "$_day start"))) + _e=$((_e + $(jitter_min "$_day end"))) + if [ "$_s" -le "$_e" ]; then + [ "$_now" -ge "$_s" ] && [ "$_now" -lt "$_e" ] + else + [ "$_now" -ge "$_s" ] || [ "$_now" -lt "$_e" ] + fi +} + +# desired state: should the tunnel be up now? (prints nothing, sets exit code) +want_up() { + [ -f "$OFF_FLAG" ] && return 1 + if [ -f "$UNTIL_FLAG" ]; then + _until=$(cat "$UNTIL_FLAG" 2>/dev/null) + case "$_until" in '' | *[!0-9]*) rm -f "$UNTIL_FLAG" ;; esac + if [ -n "$_until" ] && [ "$(date +%s)" -lt "$_until" ]; then + return 0 + fi + rm -f "$UNTIL_FLAG" + fi + [ "${OVPN_SCHED:-0}" = 1 ] || return 0 + in_window +} + +# persist KEY=value in the env file (bmstu.env) and apply it to this process, +# so the cron and the init hook that source the file pick the change up +sched_set() { + eval "$1=\$2" + [ -f "$ENV_FILE" ] || { umask 077; : > "$ENV_FILE"; } + _tmp=$(mktemp "$ENV_FILE.XXXXXX") || die "mktemp failed" + grep -v "^$1=" "$ENV_FILE" > "$_tmp" 2>/dev/null + # values here are simple (0/1 or HH:MM); single-quote so the file stays sourceable + echo "$1='$2'" >> "$_tmp" + chmod 600 "$_tmp" && mv "$_tmp" "$ENV_FILE" +} + +# the provider currently holds the direct "off" proxy (tunnel torn down) +tunnel_is_down() { grep -q "name: $PROVIDER_NAME-off" "$PROVIDER_FILE" 2>/dev/null; } + +# tear the tunnel down without touching OFF_FLAG (used by off and by the +# schedule): the kit core sends the server EXIT when the provider is replaced +tunnel_down() { + write_off_provider + wait_api + api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)" + routes_set off +} + +# bring the desired state about. repair=1 uses the two-probe test before a +# refresh of an already-up tunnel (steady-state cron); otherwise act at once. +reconcile() { + if want_up; then + if tunnel_is_down; then + log "bringing the tunnel up" + routes_set on + refresh + elif [ "${1:-}" = repair ]; then + alive && return 0 + log "probe failed, checking again" + sleep 10 + alive && return 0 + log "tunnel is down (2 failed probes), refreshing" + refresh + else + alive || refresh + fi + else + if ! tunnel_is_down; then + log "schedule: outside the window, taking the tunnel down" + tunnel_down + fi + fi +} + case "${1:-}" in otp) totp ;; # auth-user-pass file for testing with the real openvpn client @@ -298,11 +414,14 @@ case "${1:-}" in [ -f "$OFF_FLAG" ] && exit 0 wait_api alive && { log "tunnel is up"; exit 0; } + want_up || { log "schedule: outside the window, staying down"; exit 0; } refresh ;; write) - # only where OpenVPN is set up and on + # init-script hook: write a fresh-OTP provider before mihomo starts, but + # only where OpenVPN is set up and the tunnel should be up now [ -f "$OFF_FLAG" ] || [ ! -f "$PROVIDER_FILE" ] && exit 0 + want_up || { write_off_provider; exit 0; } write_provider ;; check) @@ -316,17 +435,11 @@ case "${1:-}" in fi echo $$ > "$lock/pid" trap 'rm -rf "$lock"' EXIT - alive && exit 0 - # a single lost probe on a long chain (whitelist: RU node + tunnel) is not a - # dead tunnel; refreshing then would break a working one - log "probe failed, checking again" - sleep 10 - alive && exit 0 - log "tunnel is down (2 failed probes), refreshing" - refresh + reconcile repair ;; off) touch "$OFF_FLAG" + rm -f "$UNTIL_FLAG" write_off_provider wait_api api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)" @@ -334,14 +447,52 @@ case "${1:-}" in log "OpenVPN off: tunnel closed and its routes dropped; the kit core tells the server (EXIT), other cores leave the session until its ping-restart (~5 min)" ;; on) - rm -f "$OFF_FLAG" + rm -f "$OFF_FLAG" "$UNTIL_FLAG" wait_api - routes_set on - refresh + reconcile + ;; + # bring the tunnel up for N minutes, then let the schedule resume (overrides + # the schedule while it runs; the cron takes it down when the timer expires) + for) + case "${2:-}" in '' | *[!0-9]* | 0) die "usage: bmstu-otp.sh for " ;; esac + rm -f "$OFF_FLAG" + echo "$(( $(date +%s) + $2 * 60 ))" > "$UNTIL_FLAG" + wait_api + reconcile + log "OpenVPN on for $2 min (until $(date -d "@$(cat "$UNTIL_FLAG")" '+%H:%M' 2>/dev/null || date '+%H:%M'))" + ;; + # schedule: "sched off" | "sched on" | "sched HH:MM HH:MM" (and enable). + # Persists to the env file so the cron and the init hook read the same thing. + sched) + case "${2:-}" in + '' | show) + if [ "${OVPN_SCHED:-0}" = 1 ]; then + echo "schedule on: $OVPN_SCHED_START-$OVPN_SCHED_END MSK, jitter +-$OVPN_SCHED_JITTER min" + else + echo "schedule off" + fi + exit 0 + ;; + off) sched_set OVPN_SCHED 0 ;; + on) sched_set OVPN_SCHED 1 ;; + [0-9][0-9]:[0-9][0-9]) + hhmm_to_min "$2" >/dev/null && hhmm_to_min "${3:-}" >/dev/null || die "usage: bmstu-otp.sh sched HH:MM HH:MM" + sched_set OVPN_SCHED_START "$2" + sched_set OVPN_SCHED_END "$3" + sched_set OVPN_SCHED 1 + ;; + *) die "usage: bmstu-otp.sh sched off | on | HH:MM HH:MM" ;; + esac + wait_api + reconcile ;; status) if [ -f "$OFF_FLAG" ]; then - echo "off" + echo "off (manual)" + elif [ -f "$UNTIL_FLAG" ] && [ "$(date +%s)" -lt "$(cat "$UNTIL_FLAG" 2>/dev/null || echo 0)" ]; then + echo "on by timer until $(date -d "@$(cat "$UNTIL_FLAG")" '+%H:%M' 2>/dev/null || echo '?'), $(alive && echo 'tunnel up' || echo 'tunnel down')" + elif ! want_up; then + echo "off by schedule ($OVPN_SCHED_START-$OVPN_SCHED_END MSK)" elif alive; then echo "on, tunnel is up" else diff --git a/router/bmstu.env.example b/router/bmstu.env.example index 81e5cdf..891a945 100644 --- a/router/bmstu.env.example +++ b/router/bmstu.env.example @@ -17,3 +17,11 @@ TOTP_SECRET="XXXXXXXXXXXXXXXX" #OVPN_FILE=/etc/nikki/bmstu.ovpn #PROVIDER_FILE=/etc/nikki/run/providers/bmstu.yaml + +# Schedule: with OVPN_SCHED=1 the tunnel is up only inside these local-time (MSK) +# hours, with up to OVPN_SCHED_JITTER minutes of deterministic per-day jitter on +# each edge. Managed from LuCI or `bmstu-otp.sh sched ...`; shown here for reference. +#OVPN_SCHED=0 +#OVPN_SCHED_START=09:00 +#OVPN_SCHED_END=17:00 +#OVPN_SCHED_JITTER=10 diff --git a/router/mihomo-kit.sh b/router/mihomo-kit.sh index 4330252..bda86dc 100755 --- a/router/mihomo-kit.sh +++ b/router/mihomo-kit.sh @@ -25,7 +25,7 @@ # (-f: also when the node is already logged in) # mihomo-kit.sh export > file all settings as one file; import [--keep-local] on another router # mihomo-kit.sh mobile new new secret link for the phone config (MOBILE=1) -# mihomo-kit.sh core mihomo core: stock (package) | official | kit (Tailscale fix) +# mihomo-kit.sh core mihomo core: stock (package) | official | kit (official + kit patches) # mihomo-kit.sh install packages, core, fixes, links (no questions) # mihomo-kit.sh render ... print the YAML for env file(s) (last wins) @@ -58,8 +58,8 @@ if [ -z "${MIHOMO_VERSION:-}" ]; then esac fi # where mihomo-linux--.gz is downloaded from. -tsN: own build with -# tools/core/*.patch (Tailscale through dialer-proxy, MetaCubeX/mihomo#3142) in the -# kit repo's releases; other versions: upstream MetaCubeX/mihomo releases. +# 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}" ;;