From 614f08ba168157d0b8776d61b53e65042053be5b Mon Sep 17 00:00:00 2001 From: Sam Latsin Date: Wed, 21 Oct 2026 13:30:37 +0300 Subject: [PATCH] Improved ovpn schedule --- README.md | 28 +++++++++++++------- luci/mihomo-kit.js | 46 ++++++++++++++++++++++----------- luci/rpcd.sh | 9 ++++--- router/bmstu-otp.sh | 63 +++++++++++++++++++++++++++++++++------------ 4 files changed, 101 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 7016c76..ad8678d 100644 --- a/README.md +++ b/README.md @@ -66,24 +66,32 @@ mihomo-kit.sh use main # обычный интернет в России mihomo-kit.sh use foreign # за рубежом: российское через RU, остальное напрямую 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 on # включить постоянно +bmstu-otp.sh sched on # работать по расписанию; sched off — выключить (как off) +bmstu-otp.sh sched 09:00 17:00 # запомнить часы расписания (МСК), включает их sched on bmstu-otp.sh sched 09:00 17:00 weekdays # то же, только по будням (дни: 12345, weekend, all) bmstu-otp.sh sched days 12345 # поменять только дни (1 — пн … 7 — вс) +bmstu-otp.sh for 60 # поднять на 60 минут поверх режима, потом вернуть режим +bmstu-otp.sh extend 60 # продлить таймер на 60 минут (не дальше 12 ч от сейчас) +bmstu-otp.sh stop # остановить таймер bmstu-otp.sh status # что решает сейчас, когда следующее переключение, отвечает ли туннель ``` -Эти же кнопки и поле расписания есть на странице LuCI (Службы → mihomo-kit). Там же видно, +Эти же кнопки и часы расписания есть на странице LuCI (Службы → mihomo-kit). Там же видно, что решает сейчас («включён по расписанию», «выключен вручную», «включён таймером до 15:30») и что будет дальше («выключится сегодня в 17:06», «потом снова действует ручное „Выключить“»). -Кто главнее: таймер (`for`) → ручное «Выключить» → расписание. -- «Выключить» держится, пока не нажмёшь «Включить»: расписание его не снимает. -- Таймер поднимает туннель поверх всего, а когда истекает, возвращает то, что было до него: - ручное выключение или расписание. «Выключить» во время таймера его отменяет. -- «Включить» снимает ручное выключение и таймер, дальше решает расписание: вне окна туннель - останется выключенным, поднять его там можно таймером. Без расписания туннель включён всегда. +Режим всегда один из трёх, у каждого своя кнопка: +- «Включить» — туннель включён постоянно; +- «Выключить» — выключен и сам не включится; +- «Включить расписание» — включён только в часы и дни расписания. «Выключить расписание» + переводит в «Выключено». Выключенное расписание туннель не включает; «Сохранить» у часов + только запоминает их. + +«Включить» и «Выключить» снимают расписание и таймер. Таймер («Включить на 1 ч», потом +«+1 ч», не дальше 12 ч от текущего момента — `TIMER_MAX`) поднимает туннель поверх любого +режима, а когда истекает или по «Остановить таймер», возвращает режим. Так можно держать +OpenVPN выключенным и включать его только на время, не трогая расписание. Дни недели — галки Пн…Вс рядом с расписанием (`OVPN_SCHED_DAYS` в `bmstu.env`, по умолчанию все); окно через полночь относится ко дню, в который началось: «22:00–02:00 по будням» работает и diff --git a/luci/mihomo-kit.js b/luci/mihomo-kit.js index d3828de..9e20e04 100644 --- a/luci/mihomo-kit.js +++ b/luci/mihomo-kit.js @@ -57,7 +57,7 @@ function ovpnMode(o) { break; case 'manual': r.now = 'выключен вручную'; - r.next = 'сам не включится: расписание не действует, пока не нажмёшь «Включить» (или «на 1 ч»)'; + r.next = 'сам не включится: «Включить», «Включить расписание» или «на 1 ч»'; break; case 'schedule': r.now = o.want ? 'включён по расписанию' : 'выключен по расписанию'; @@ -317,7 +317,6 @@ return view.extend({ var modeNow = E('span', '—'); var modeNext = 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 dayNames = [ 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс' ]; @@ -362,12 +361,18 @@ return view.extend({ dom.content(modeNow, [ E('strong', m.now) ].concat(m.pending ? [ ' — ', E('span', { 'class': 'cbi-value-description' }, m.pending) ] : [])); dom.content(modeNext, m.next || '—'); - dom.content(schedInfo, o.sched - ? daysText(o.sched_days) + ' с ' + o.sched_start + ' до ' + o.sched_end + ' (МСК), границы сдвигаются до ±' + o.jitter + + dom.content(schedInfo, o.sched_start + ? (o.sched_active ? 'включено: ' : 'выключено (часы сохранены): ') + daysText(o.sched_days) + ' с ' + o.sched_start + ' до ' + o.sched_end + ' (МСК), границы сдвигаются до ±' + o.jitter + ' мин' + (o.win ? '; сегодня ' + o.win.replace('-', '–') : '') : 'выключено'); + // one of each pair, by the state: timer running or not, schedule on or not + var timer = o.mode == 'timer'; + timerStart.style.display = timer ? 'none' : ''; + timerMore.style.display = timerStop.style.display = timer ? '' : 'none'; + timerMore.disabled = timer && o.until - Date.now() / 1000 > o.timer_max * 60 - 120; + schedStartBtn.style.display = o.sched_active ? 'none' : ''; + schedStopBtn.style.display = o.sched_active ? '' : 'none'; if (!schedFilled) { - schedOn.checked = !!o.sched; if (o.sched_start) schedStart.value = o.sched_start; if (o.sched_end) schedEnd.value = o.sched_end; if (o.sched_days) @@ -376,6 +381,14 @@ return view.extend({ } }).catch(function(e) { dom.content(ovpnState, String(e)); }); }; + var timerStart = this.button('Включить на 1 ч', 'action', 'ovpn-for', '60'); + var timerMore = this.button('+1 ч', 'action', 'ovpn-extend', '60'); + var timerStop = this.button('Остановить таймер', 'negative', 'ovpn-stop'); + timerMore.style.display = timerStop.style.display = 'none'; + var schedStartBtn = this.button('Включить расписание', 'positive', 'ovpn-sched', 'on'); + var schedStopBtn = this.button('Выключить расписание', 'negative', 'ovpn-sched', 'off', + 'Выключить расписание? Туннель выключится и сам не включится, пока не нажмёшь «Включить» или «Включить расписание».'); + schedStopBtn.style.display = 'none'; ovpnCheck(); sections.push(section('OpenVPN', [ E('table', { 'class': 'table' }, [ @@ -400,26 +413,29 @@ return view.extend({ row('Расписание', schedInfo) ]), E('div', { 'class': 'cbi-page-actions' }, [ - this.button('Включить', 'positive', 'ovpn-on'), ' ', - this.button('Включить на 1 ч', 'action', 'ovpn-for', '60'), ' ', + this.button('Включить', 'positive', 'ovpn-on', null, + 'Включить постоянно? Расписание и таймер выключатся.'), ' ', this.button('Выключить', 'negative', 'ovpn-off', null, - 'Закрыть туннель и держать выключенным, пока не нажмёшь «Включить»? ' + + 'Закрыть туннель и держать выключенным, пока не нажмёшь «Включить» или «Включить расписание»? ' + + 'Расписание и таймер выключатся. ' + 'С ядром kit сессия на сервере освобождается сразу, с другим ядром — через ~5 минут.'), ' ', + schedStartBtn, schedStopBtn, ' ', + timerStart, timerMore, ' ', timerStop, ' ', this.button('Переподключить', 'action', 'ovpn-refresh') ]), - field('Расписание (MSK)', [ schedOn, ' ', schedStart, ' – ', schedEnd, ' ', + field('Часы расписания (MSK)', [ schedStart, ' – ', schedEnd, ' ', E('span', { 'style': 'white-space:nowrap' }, schedDays.reduce(function(a, c, i) { return a.concat([ ' ', E('label', [ c, ' ', dayNames[i] ]) ]); }, [])), ' ', this.button('Сохранить', 'action', 'ovpn-sched', function() { var d = schedDays.reduce(function(a, c, i) { return c.checked ? a + (i + 1) : a; }, ''); - return schedOn.checked ? schedStart.value + ' ' + schedEnd.value + ' ' + d : 'off'; + return schedStart.value + ' ' + schedEnd.value + ' ' + d; }) ], - 'Туннель работает только в эти часы и в отмеченные дни; окно через полночь относится ко дню, ' + - 'в который началось. Кто главнее: «на 1 ч» → «Выключить» → расписание. ' + - '«Выключить» держится, пока не нажмёшь «Включить», расписание его не снимает. ' + - '«на 1 ч» поднимает туннель поверх всего, а по окончании возвращает как было: ручное выключение или расписание. ' + - '«Включить» снимает ручное выключение и таймер, дальше решает расписание (вне окна туннель останется выключенным).') + '«Сохранить» только запоминает часы и дни, включает их «Включить расписание». ' + + 'Режим один из трёх: «Включить» — постоянно, «Выключить» — выключен, «Включить расписание» — ' + + 'только в эти часы и в отмеченные дни (окно через полночь относится ко дню, в который началось). ' + + 'Выключенное расписание туннель не включает. Таймер («на 1 ч», «+1 ч», до 12 ч вперёд) поднимает туннель ' + + 'поверх любого режима, а по окончании или «Остановить таймер» возвращает режим.') ])); } diff --git a/luci/rpcd.sh b/luci/rpcd.sh index b60b91b..85980ca 100644 --- a/luci/rpcd.sh +++ b/luci/rpcd.sh @@ -132,12 +132,12 @@ m_ovpn_status() { # 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_start|sched_end|sched_days|jitter)=([A-Za-z0-9:._-]*)$/st_\1=\2/p' \ + 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 jitter; do + 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)" @@ -177,10 +177,11 @@ 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) + ovpn-for | ovpn-extend) case "$arg" in '' | *[!0-9]* | 0) reply_error "bad minutes" ;; esac - set -- bmstu-otp.sh for "$arg" + 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 diff --git a/router/bmstu-otp.sh b/router/bmstu-otp.sh index a52fd72..7a52a50 100755 --- a/router/bmstu-otp.sh +++ b/router/bmstu-otp.sh @@ -24,15 +24,21 @@ # bmstu-otp.sh write only regenerate the provider and routes (nikki init, before mihomo starts) # bmstu-otp.sh check reconcile to the desired state (timer/manual/schedule) and # refresh a dead tunnel (cron, once a minute; no traffic with the kit core) -# bmstu-otp.sh for N up for N minutes over the manual off and the schedule, then back -# to whatever held before -# bmstu-otp.sh sched ... off | on | HH:MM HH:MM [DAYS] | days DAYS: work-hours schedule -# (MSK; DAYS 12345 | weekdays | weekend | all), persisted -# bmstu-otp.sh off close the tunnel and keep it closed (sticky, wins over the schedule, -# cancels a timer; BMSTU traffic goes without it); frees the single -# server session (the kit core sends EXIT; other cores leave it until +# Three modes, one at a time: on (always), off, schedule. A timer runs over any of them +# and hands back to the mode when it ends. +# bmstu-otp.sh on always on: drops the manual off, the schedule and the timer +# bmstu-otp.sh off close the tunnel and keep it closed: drops the schedule and the +# timer (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 drop the manual off and the timer: the schedule (if any) decides +# bmstu-otp.sh sched on the schedule decides (drops the manual off; the timer stays) +# bmstu-otp.sh sched off schedule off, the tunnel off (as "off", the timer stays) +# bmstu-otp.sh sched HH:MM HH:MM [DAYS] | days DAYS: only store the work hours +# (MSK; DAYS 12345 | weekdays | weekend | all); "sched on" uses them +# bmstu-otp.sh for N up for N minutes from now over the mode, then back to it +# bmstu-otp.sh extend N N more minutes on the timer (starts one if none runs); a timer +# never reaches past TIMER_MAX minutes from now +# bmstu-otp.sh stop end the timer now, back to the mode # bmstu-otp.sh status what decides now, the next change, the tunnel state (no traffic) # bmstu-otp.sh probe open CHECK_URL through the tunnel (a request the site can log) # bmstu-otp.sh state the same as key=value lines (LuCI) @@ -67,6 +73,8 @@ api_from_uci() { # 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}" +# the longest a timer (for / extend) reaches from now, minutes +: "${TIMER_MAX:=720}" # 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. @@ -697,6 +705,11 @@ state() { echo "win=$(min_to_hhmm "$_s")-$(min_to_hhmm "$_e")" fi echo "sched=${OVPN_SCHED:-0}" + # the schedule decides (the mode is "schedule": not under a manual off) + _sa=0 + [ "${OVPN_SCHED:-0}" = 1 ] && [ ! -f "$OFF_FLAG" ] && _sa=1 + echo "sched_active=$_sa" + echo "timer_max=$TIMER_MAX" echo "sched_start=$OVPN_SCHED_START" echo "sched_end=$OVPN_SCHED_END" echo "sched_days=$OVPN_SCHED_DAYS" @@ -815,28 +828,41 @@ case "${1:-}" in lock_wait touch "$OFF_FLAG" rm -f "$UNTIL_FLAG" + [ "${OVPN_SCHED:-0}" = 1 ] && sched_set OVPN_SCHED 0 tunnel_down 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) lock_wait rm -f "$OFF_FLAG" "$UNTIL_FLAG" + [ "${OVPN_SCHED:-0}" = 1 ] && sched_set OVPN_SCHED 0 wait_api reconcile ;; # bring the tunnel up for N minutes, over the manual off and the schedule; # then whatever was in force before holds again (the cron applies it) - for) - case "${2:-}" in '' | *[!0-9]* | 0) die "usage: bmstu-otp.sh for " ;; esac + for | extend) + case "${2:-}" in '' | *[!0-9]* | 0) die "usage: bmstu-otp.sh $1 " ;; esac lock_wait - echo "$(($(date +%s) + $2 * 60))" > "$UNTIL_FLAG" + _now=$(date +%s) + # extend: from the end of the running timer, from now when none runs + [ "$1" = extend ] && _from=$(timer_until) || _from=$_now + _end=$((_from + $2 * 60)) + [ "$_end" -gt $((_now + TIMER_MAX * 60)) ] && _end=$((_now + TIMER_MAX * 60)) + echo "$_end" > "$UNTIL_FLAG" wait_api reconcile rc=$? eval "$(state)" - log "OpenVPN on for $2 min, until $until_hm; then $after ($why)" + log "OpenVPN on by timer until $until_hm $until_day; then $after ($why)" exit $rc ;; + stop) + lock_wait + rm -f "$UNTIL_FLAG" + wait_api + reconcile + ;; # schedule: "sched off" | "sched on" | "sched HH:MM HH:MM [DAYS]" (and enable) | # "sched days DAYS"; DAYS: digits 1 (Mon) .. 7 (Sun), weekdays, weekend, all. # Persists to the env file so the cron and the init hook read the same thing. @@ -853,8 +879,14 @@ case "${1:-}" in esac lock_wait case "$2" in - off) sched_set OVPN_SCHED 0 ;; - on) sched_set OVPN_SCHED 1 ;; + off) + sched_set OVPN_SCHED 0 + touch "$OFF_FLAG" + ;; + on) + rm -f "$OFF_FLAG" + sched_set OVPN_SCHED 1 + ;; days) _dz=$(days_norm "${3:-}") && [ -n "$_dz" ] || die "usage: bmstu-otp.sh sched days 12345 | weekdays | weekend | all" sched_set OVPN_SCHED_DAYS "$_dz" @@ -873,7 +905,6 @@ case "${1:-}" in fi 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 [DAYS] | days DAYS" ;; esac @@ -934,5 +965,5 @@ case "${1:-}" in echo "--- handshake errors ---" { cat /var/log/nikki/core.log 2>/dev/null || logread; } | grep -E "OpenVPN" | tail -n 5 ;; - *) echo "usage: $0 otp|authfile|refresh|check|on|off|status|debug" >&2; exit 2 ;; + *) echo "usage: $0 otp|authfile|refresh|check|on|off|sched|for|extend|stop|status|debug" >&2; exit 2 ;; esac