diff --git a/README.md b/README.md index 7235804..da14fd6 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,8 @@ 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 sched 09:00 17:00 weekdays # то же, только по будням (дни: 12345, weekend, all) +bmstu-otp.sh sched days 12345 # поменять только дни (1 — пн … 7 — вс) bmstu-otp.sh status # что решает сейчас, когда следующее переключение, отвечает ли туннель ``` @@ -80,6 +82,10 @@ bmstu-otp.sh status # что решает сейчас, когда с - «Включить» снимает ручное выключение и таймер, дальше решает расписание: вне окна туннель останется выключенным, поднять его там можно таймером. Без расписания туннель включён всегда. +Дни недели — галки Пн…Вс рядом с расписанием (`OVPN_SCHED_DAYS` в `bmstu.env`, по умолчанию +все); окно через полночь относится ко дню, в который началось: «22:00–02:00 по будням» работает и +в ночь с пятницы на субботу, но не с воскресенья на понедельник. + Время — локальное на роутере (МСК). Границы окна каждый день сдвигаются на случайные, но постоянные в течение дня ±10 минут (`OVPN_SCHED_JITTER`), чтобы включение и выключение не приходились каждый раз на одну и ту же секунду. Поэтому окно короче 20 минут (или длиннее @@ -201,7 +207,14 @@ CSQTT ([star-panel-csqtt](https://github.com/starkugz/csqtt-openwrt)) — рез `MY` / `RU` работают поверх него как обычно. На `whitelist` свои серверы идут цепочкой `MY-EXIT` → нода → `CSQTT`. -Переключается в дашборде, без перезапуска. `CSQTT` ещё есть последним пунктом в `MAIN` — +Включать и выключать — кнопками в блоке «CSQTT» на странице mihomo-kit (или +`mihomo-kit.sh csqtt on|off`): «Включить» запускает csqtt, ждёт подключения (до 90 с, +`CSQTT_WAIT`) и только потом ставит `UPLINK = CSQTT`; «Выключить» сначала возвращает +`UPLINK = DIRECT`, потом останавливает csqtt и ставит `csqtt.main.enabled=0` — без этого он +поднимается сам при перезагрузке и переподключении WAN. Там же состояние: подключён ли, +активный профиль, трафик, капчи и последняя ошибка (`User authorization failed` — истёк +VK-токен). Кнопка Stop в панели csqtt останавливает только процесс. `UPLINK` можно +переключать и в дашборде, без перезапуска. `CSQTT` ещё есть последним пунктом в `MAIN` — просто выход в интернет с IP сервера CSQTT. Правила `DIRECT` (ru-inside, `.ru` на `main`) в туннель не идут. diff --git a/luci/acl.json b/luci/acl.json index e41b4e6..e6f95a7 100644 --- a/luci/acl.json +++ b/luci/acl.json @@ -1,9 +1,9 @@ { "luci-app-mihomo-kit": { - "description": "mihomo-kit: profiles, OpenVPN, Tailscale", + "description": "mihomo-kit: profiles, OpenVPN, Tailscale, CSQTT", "read": { "ubus": { - "mihomo-kit": [ "status", "ovpn_status", "ovpn_probe", "job", "update_check", "ts_check" ] + "mihomo-kit": [ "status", "ovpn_status", "ovpn_probe", "csqtt_status", "job", "update_check", "ts_check" ] } }, "write": { diff --git a/luci/mihomo-kit.js b/luci/mihomo-kit.js index da566e3..2f27ebf 100644 --- a/luci/mihomo-kit.js +++ b/luci/mihomo-kit.js @@ -14,6 +14,7 @@ var callOvpnStatus = rpc.declare({ object: 'mihomo-kit', method: 'ovpn_status', var callOvpnProbe = rpc.declare({ object: 'mihomo-kit', method: 'ovpn_probe', nobatch: true, expect: { '': {} } }); var callJob = rpc.declare({ object: 'mihomo-kit', method: 'job', expect: { '': {} } }); var callRun = rpc.declare({ object: 'mihomo-kit', method: 'run', params: [ 'cmd', 'arg' ], expect: { '': {} } }); +var callCsqttStatus = rpc.declare({ object: 'mihomo-kit', method: 'csqtt_status', nobatch: true, expect: { '': {} } }); var callTsCheck = rpc.declare({ object: 'mihomo-kit', method: 'ts_check', nobatch: true, expect: { '': {} } }); var callUpdateCheck = rpc.declare({ object: 'mihomo-kit', method: 'update_check', nobatch: true, expect: { '': {} } }); var callExport = rpc.declare({ object: 'mihomo-kit', method: 'export', expect: { '': {} } }); @@ -317,6 +318,17 @@ return view.extend({ 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 = [ 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс' ]; + // at least one day stays checked + var schedDays = dayNames.map(function() { + return E('input', { 'type': 'checkbox', 'checked': true, 'change': function(ev) { + if (!schedDays.some(function(c) { return c.checked; })) ev.target.checked = true; + } }); + }); + var daysText = function(d) { + return d == '1234567' || !d ? 'каждый день' : d == '12345' ? 'по будням' : d == '67' ? 'по выходным' + : d.split('').map(function(x) { return dayNames[x - 1]; }).join(', '); + }; var schedFilled = false; var desc = function(t) { return E('span', { 'class': 'cbi-value-description' }, t); }; // the state comes from the kit core through the API: no traffic in the tunnel @@ -341,13 +353,15 @@ return view.extend({ ? [ ' — ', E('span', { 'class': 'cbi-value-description' }, m.pending) ] : [])); dom.content(modeNext, m.next || '—'); dom.content(schedInfo, o.sched - ? 'с ' + o.sched_start + ' до ' + o.sched_end + ' (МСК), границы сдвигаются до ±' + o.jitter + + ? daysText(o.sched_days) + ' с ' + o.sched_start + ' до ' + o.sched_end + ' (МСК), границы сдвигаются до ±' + o.jitter + ' мин' + (o.win ? '; сегодня ' + o.win.replace('-', '–') : '') : 'выключено'); 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) + schedDays.forEach(function(c, i) { c.checked = o.sched_days.indexOf(String(i + 1)) >= 0; }); schedFilled = true; } }).catch(function(e) { dom.content(ovpnState, String(e)); }); @@ -384,16 +398,63 @@ return view.extend({ this.button('Переподключить', 'action', 'ovpn-refresh') ]), field('Расписание (MSK)', [ schedOn, ' ', 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() { - return schedOn.checked ? schedStart.value + ' ' + schedEnd.value : 'off'; + var d = schedDays.reduce(function(a, c, i) { return c.checked ? a + (i + 1) : a; }, ''); + return schedOn.checked ? schedStart.value + ' ' + schedEnd.value + ' ' + d : 'off'; }) ], - 'Туннель работает только в эти часы. Кто главнее: «на 1 ч» → «Выключить» → расписание. ' + + 'Туннель работает только в эти часы и в отмеченные дни; окно через полночь относится ко дню, ' + + 'в который началось. Кто главнее: «на 1 ч» → «Выключить» → расписание. ' + '«Выключить» держится, пока не нажмёшь «Включить», расписание его не снимает. ' + '«на 1 ч» поднимает туннель поверх всего, а по окончании возвращает как было: ручное выключение или расписание. ' + '«Включить» снимает ручное выключение и таймер, дальше решает расписание (вне окна туннель останется выключенным).') ])); } + if (st.csqtt) { + var cqState = E('span', '—'); + var cqUplink = E('span', '—'); + var cqInfo = E('span', '—'); + var cqCheck = function() { + dom.content(cqState, E('em', 'обновляю…')); + return callCsqttStatus().then(function(c) { + dom.content(cqState, [ { + up: E('strong', { 'style': 'color:green' }, 'подключён' + (c.active ? ' (' + c.active + ')' : '')), + connecting: E('strong', { 'style': 'color:#c60' }, 'подключается' + (c.stage ? ' (' + c.stage + ')' : '')), + stopped: E('strong', c.enabled ? 'остановлен' : 'выключен') + }[c.link] || c.link || '—' ] + .concat(c.captcha ? [ ' — ', E('strong', { 'style': 'color:#c00' }, 'капча: ' + c.captcha + + ' (star-panel-csqtt → CAPTCHA)') ] : []) + .concat(c.err ? [ E('div', { 'class': 'cbi-value-description' }, 'последняя ошибка: ' + c.err + + (/authorization failed/i.test(c.err) ? ' — нужен новый VK-токен' : '')) ] : [])); + dom.content(cqUplink, c.uplink == 'CSQTT' + ? E('strong', 'CSQTT — ноды подключаются через туннель') + : c.uplink == 'DIRECT' ? 'DIRECT — как без CSQTT' : (c.uplink || 'mihomo не отвечает')); + dom.content(cqInfo, c.stats || '—'); + }).catch(function(e) { dom.content(cqState, String(e)); }); + }; + if (st.csqtt_installed) + cqCheck(); + sections.push(section('CSQTT', st.csqtt_installed ? [ + E('table', { 'class': 'table' }, [ + row('Туннель', [ cqState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action', + 'click': ui.createHandlerFn(this, cqCheck) }, 'Обновить') ]), + row('UPLINK', cqUplink), + row('Трафик', cqInfo) + ]), + E('div', { 'class': 'cbi-page-actions' }, [ + this.button('Включить', 'positive', 'csqtt-on'), ' ', + this.button('Выключить', 'negative', 'csqtt-off') + ]), + E('p', { 'class': 'cbi-value-description' }, + '«Включить»: запускает csqtt, ждёт подключения (до 1,5 мин) и ставит UPLINK = CSQTT. ' + + '«Выключить»: UPLINK = DIRECT, затем останавливает csqtt — он не поднимется сам ни после ' + + 'перезагрузки, ни при переподключении WAN. Профили и VK-токен — в Службы → star-panel-csqtt.') + ] : [ E('p', 'csqtt не установлен: поставь star-panel-csqtt (github.com/starkugz/csqtt-openwrt).') ])); + } + if (st.tailscale) { var tsState = E('span', '—'); var tsCheck = function() { diff --git a/luci/rpcd.sh b/luci/rpcd.sh index da8ce61..0bf24b8 100644 --- a/luci/rpcd.sh +++ b/luci/rpcd.sh @@ -6,6 +6,7 @@ # 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 @@ -72,6 +73,8 @@ m_status() { 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 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) @@ -126,9 +129,9 @@ 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|until|until_hm|until_day|after|why|next|next_to|next_hm|next_day|win|sched|sched_start|sched_end|jitter)=([A-Za-z0-9:._-]*)$/st_\1=\2/p' \ + sed -En -e 's/^(mode|want|tunnel|link|up_since|up_hm|up_day|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' \ -e "s/^err='([^'\`\$\\\\]*)'\$/st_err='\\1'/p")" - for k in mode tunnel link up_hm up_day err until_hm until_day after why next_to next_hm next_day win sched_start sched_end; do + for k in mode tunnel link up_hm up_day 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 @@ -139,6 +142,20 @@ m_ovpn_status() { 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 @@ -162,9 +179,12 @@ m_run() { set -- bmstu-otp.sh for "$arg" ;; ovpn-sched) - # arg: "off" | "on" | "HH:MM HH:MM"; unquoted below to split the two times + # 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 @@ -175,6 +195,8 @@ m_run() { 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 ;; @@ -414,13 +436,14 @@ m_job() { case "$1" in list) - echo '{"status":{},"ovpn_status":{},"ovpn_probe":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{},"export":{},"import":{"data":"str","keep_local":true}}' + 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 ;; diff --git a/router/bmstu-otp.sh b/router/bmstu-otp.sh index 54e8ff1..8256dfe 100755 --- a/router/bmstu-otp.sh +++ b/router/bmstu-otp.sh @@ -26,7 +26,8 @@ # 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: work-hours schedule (MSK), persisted +# 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 @@ -69,7 +70,10 @@ api_from_uci() { # 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_DAYS: weekdays the window opens on, digits 1 (Mon) .. 7 (Sun); a window +# past midnight belongs to the day it starts on. : "${OVPN_SCHED:=0}" "${OVPN_SCHED_START:=09:00}" "${OVPN_SCHED_END:=17:00}" "${OVPN_SCHED_JITTER:=10}" +: "${OVPN_SCHED_DAYS:=1234567}" # what "probe" opens through the tunnel: OVPN_CHECK_URL of the profiles (LuCI) : "${CHECK_URL:=$(sed -n 's/^OVPN_CHECK_URL=//p' /etc/nikki/profiles.d/common.env 2>/dev/null | tail -n 1 | tr -d "'\"")}" : "${CHECK_URL:=https://eu.bmstu.ru}" @@ -452,17 +456,52 @@ sched_edges() { _e=$((_e + $(jitter_min "$1 end"))) } +# weekday of YYYY-MM-DD, 1 (Mon) .. 7 (Sun), plain arithmetic (Sakamoto) +dow_of() { + _y=${1%%-*} _mo=${1#*-} _dd=${1##*-} + _mo=${_mo%-*} _mo=${_mo#0} _dd=${_dd#0} + [ "$_mo" -lt 3 ] && _y=$((_y - 1)) + set -- 0 3 2 5 0 3 5 1 4 6 2 4 + shift $((_mo - 1)) + _w=$(((_y + _y / 4 - _y / 100 + _y / 400 + $1 + _dd) % 7)) + echo $((_w == 0 ? 7 : _w)) +} + +# day_on <1..7>: the window opens on that weekday (OVPN_SCHED_DAYS) +day_on() { case "$OVPN_SCHED_DAYS" in *"$1"*) return 0 ;; esac; return 1; } + +# days_norm <1234567 | weekdays | weekend | all | digits>: sorted digits 1..7, or nothing +days_norm() { + case "$1" in + all | '') set -- 1234567 ;; + weekdays) set -- 12345 ;; + weekend) set -- 67 ;; + *[!1-7]*) return 1 ;; + esac + _o="" + for _x in 1 2 3 4 5 6 7; do + case "$1" in *"$_x"*) _o=$_o$_x ;; esac + done + echo "$_o" +} + # in_window [day minute]: true when that moment (default: now) is inside the -# jittered window of the day; a window with END < START wraps past midnight. +# jittered window of the day; a window with END < START wraps past midnight, its +# part after midnight belongs to the previous day (OVPN_SCHED_DAYS). # A malformed setting counts as inside. NOW_MIN/SCHED_DAY override the clock in tests. in_window() { _day=${1:-${SCHED_DAY:-$(date +%F)}} _now=${2:-${NOW_MIN:-$(hhmm_to_min "$(date +%H:%M)")}} sched_edges "$_day" || return 0 + _dw=$(dow_of "$_day") if [ "$_s" -le "$_e" ]; then - [ "$_now" -ge "$_s" ] && [ "$_now" -lt "$_e" ] + day_on "$_dw" && [ "$_now" -ge "$_s" ] && [ "$_now" -lt "$_e" ] + elif [ "$_now" -ge "$_s" ]; then + day_on "$_dw" + elif [ "$_now" -lt "$_e" ]; then + day_on $((_dw == 1 ? 7 : _dw - 1)) else - [ "$_now" -ge "$_s" ] || [ "$_now" -lt "$_e" ] + return 1 fi } @@ -501,31 +540,37 @@ want_up() { return 1 } -# next schedule edge after now -> _next (epoch) _next_to (on|off); the window -# check of sched keeps today's and tomorrow's windows the same shape +# next schedule change after now -> _next (epoch) _next_to (on|off). Walks the +# candidate moments (midnight and the jittered edges of each day, up to 8 days +# ahead: weekdays may be skipped) and asks in_window, so both always agree. sched_next() { _t=$(date +%s) set -- $(date -d "@$_t" '+%F %H:%M %S') _m=$(hhmm_to_min "$2") || return 1 _mid=$((_t - _m * 60 - ${3#0})) sched_edges "$1" || return 1 - _s0=$_s _e0=$_e - sched_edges "$(date -d "@$((_mid + 86400 + 3600))" +%F)" || return 1 - if [ "$_s0" -le "$_e0" ]; then - if [ "$_m" -lt "$_s0" ]; then - _next=$((_mid + _s0 * 60)) _next_to=on - elif [ "$_m" -lt "$_e0" ]; then - _next=$((_mid + _e0 * 60)) _next_to=off - else - _next=$((_mid + 86400 + _s * 60)) _next_to=on - fi - elif [ "$_m" -lt "$_e0" ]; then - _next=$((_mid + _e0 * 60)) _next_to=off - elif [ "$_m" -lt "$_s0" ]; then - _next=$((_mid + _s0 * 60)) _next_to=on - else - _next=$((_mid + 86400 + _e * 60)) _next_to=off - fi + _cur=0 + in_window "$1" "$_m" && _cur=1 + _k=0 + while [ "$_k" -le 8 ]; do + _d=$1 + [ "$_k" -gt 0 ] && _d=$(date -d "@$((_mid + _k * 86400 + 3600))" +%F) + sched_edges "$_d" + if [ "$_s" -le "$_e" ]; then _cs="0 $_s $_e"; else _cs="0 $_e $_s"; fi + for _c in $_cs; do + [ "$_c" -ge 0 ] && [ "$_c" -le 1439 ] || continue + [ "$_k" -eq 0 ] && [ "$_c" -le "$_m" ] && continue + _on=0 + in_window "$_d" "$_c" && _on=1 + if [ "$_on" != "$_cur" ]; then + _next=$((_mid + _k * 86400 + _c * 60)) _next_to=off + [ "$_on" = 1 ] && _next_to=on + return 0 + fi + done + _k=$((_k + 1)) + done + return 1 } # epoch -> "HH:MM today|tomorrow|YYYY-MM-DD" in router-local time @@ -551,7 +596,7 @@ when() { # after on | off once the timer ends, why: manual | schedule | always # next next schedule change (epoch, 0 = none), next_to on | off, next_hm, next_day # win today's window with the jitter, HH:MM-HH:MM -# sched sched_start sched_end jitter: the settings +# sched sched_start sched_end sched_days jitter: the settings state() { _until=$(timer_until) || _until=0 set -- $(base_state) @@ -613,6 +658,7 @@ state() { echo "sched=${OVPN_SCHED:-0}" echo "sched_start=$OVPN_SCHED_START" echo "sched_end=$OVPN_SCHED_END" + echo "sched_days=$OVPN_SCHED_DAYS" echo "jitter=$OVPN_SCHED_JITTER" } @@ -750,13 +796,14 @@ case "${1:-}" in log "OpenVPN on for $2 min, until $until_hm; then $after ($why)" exit $rc ;; - # schedule: "sched off" | "sched on" | "sched HH:MM HH:MM" (and enable). + # 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. 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" + echo "schedule on: $OVPN_SCHED_START-$OVPN_SCHED_END MSK, days $OVPN_SCHED_DAYS, jitter +-$OVPN_SCHED_JITTER min" else echo "schedule off" fi @@ -767,6 +814,10 @@ case "${1:-}" in case "$2" in off) sched_set OVPN_SCHED 0 ;; on) 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" + ;; [0-9][0-9]:[0-9][0-9]) _a=$(hhmm_to_min "$2") && _b=$(hhmm_to_min "${3:-}") || die "usage: bmstu-otp.sh sched HH:MM HH:MM" # the jittered edges must not cross, or the window flips between @@ -775,11 +826,15 @@ case "${1:-}" in _len=$(((_b - _a + 1440) % 1440)) [ "$_len" -gt "$_j" ] && [ "$_len" -lt $((1440 - _j)) ] || die "the window must be longer than $_j min and shorter than 24 h minus $_j min (jitter +-${OVPN_SCHED_JITTER:-0} min)" + if [ -n "${4:-}" ]; then + _dz=$(days_norm "$4") && [ -n "$_dz" ] || die "days: digits 1 (Mon) .. 7 (Sun), weekdays, weekend or all" + sched_set OVPN_SCHED_DAYS "$_dz" + 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" ;; + *) die "usage: bmstu-otp.sh sched off | on | HH:MM HH:MM [DAYS] | days DAYS" ;; esac wait_api reconcile @@ -806,7 +861,7 @@ case "${1:-}" in ;; esac if [ "$next" -gt 0 ]; then - echo "schedule: $sched_start-$sched_end MSK, today $win (jitter +-$jitter min)" + echo "schedule: $sched_start-$sched_end MSK, days $sched_days, today $win (jitter +-$jitter min)" [ "$mode" = schedule ] && echo "turns $next_to at $next_hm $next_day" fi case "$link" in diff --git a/router/mihomo-kit.sh b/router/mihomo-kit.sh index 4221c64..d22c56c 100755 --- a/router/mihomo-kit.sh +++ b/router/mihomo-kit.sh @@ -22,6 +22,7 @@ # mihomo-kit.sh auto-update [on|off] daily 04:00 update via cron; no argument = run it now # 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 +# mihomo-kit.sh csqtt on|off|state CSQTT tunnel (star-panel-csqtt) + group UPLINK, in order # (-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) @@ -626,6 +627,76 @@ cmd_use() { return 0 } +# --- CSQTT on/off ------------------------------------------------------------ +# The csqtt service (star-panel-csqtt) and the group UPLINK, always in this order, +# so the nodes never dial through a missing csqtt0: +# on main.enabled=1 + start, wait until connected (csqtt status = 0), UPLINK=CSQTT +# off UPLINK=DIRECT, then stop + main.enabled=0 (stays off on boot / WAN up) +# state key=value lines for LuCI (no traffic through the tunnel) +CSQTT_WAIT=${CSQTT_WAIT:-90} + +uplink_now() { api_get /proxies/UPLINK 2>/dev/null | jsonfilter -e '@.now' 2>/dev/null; } +uplink_set() { + api_get /proxies/UPLINK -X PUT -H 'Content-Type: application/json' -d "{\"name\":\"$1\"}" >/dev/null 2>&1 +} + +# csqtt status (exit 0 connected, 1 not, 2 service not running) -> _cq_rc, _cq_out +csqtt_status() { + _cq_out=$(csqtt status 2>/dev/null) + _cq_rc=$? +} + +# single-quoted, without characters that break eval in rpcd +cq_quote() { printf "'%s'" "$(printf '%s' "$1" | tr -d "'\"\`\\\\\$\n" | cut -c1-200)"; } + +cmd_csqtt() { + command -v csqtt >/dev/null 2>&1 || die "csqtt is not installed (star-panel-csqtt)" + case "${1:-}" in + on) + [ -n "$(uplink_now)" ] || die "no group UPLINK in the running profile: tick CSQTT in the settings (CSQTT=1), save and apply" + uci set csqtt.main.enabled=1 + uci commit csqtt + /etc/init.d/csqtt start + log "csqtt: waiting for the tunnel, up to $CSQTT_WAIT s" + _w=0 + while csqtt_status; [ "$_cq_rc" != 0 ]; do + if [ "$_w" -ge "$CSQTT_WAIT" ]; then + printf '%s\n' "$_cq_out" | grep -E '^(connectivity|last error|captcha):' >&2 + die "csqtt did not connect in $CSQTT_WAIT s; UPLINK stays $(uplink_now), the service keeps trying (press again later)" + fi + sleep 3 + _w=$((_w + 3)) + done + uplink_set CSQTT || die "csqtt is up, but UPLINK=CSQTT failed (mihomo API)" + log "csqtt connected, UPLINK=CSQTT: the nodes now connect through ${CSQTT_IFACE:-csqtt0}" + ;; + off) + if [ -n "$(uplink_now)" ]; then + uplink_set DIRECT && log "UPLINK=DIRECT" || log "warning: UPLINK=DIRECT failed (mihomo API)" + fi + uci set csqtt.main.enabled=0 + uci commit csqtt + /etc/init.d/csqtt stop + log "csqtt stopped (main.enabled=0: it stays off until csqtt on)" + ;; + state) + csqtt_status + case "$_cq_rc" in 0) _l=up ;; 2) _l=stopped ;; *) _l=connecting ;; esac + echo "link=$_l" + echo "enabled=$(uci -q get csqtt.main.enabled || echo 0)" + echo "uplink=$(uplink_now)" + echo "active=$(printf '%s\n' "$_cq_out" | sed -n 's/^selection:.*active: *\([A-Za-z0-9_.-]*\).*/\1/p')" + echo "stage=$(printf '%s\n' "$_cq_out" | sed -n 's/^connectivity: *stage=\([A-Za-z0-9_-]*\).*/\1/p')" + echo "captcha=$(printf '%s\n' "$_cq_out" | sed -n 's/^captcha: *\([0-9]*\) pending.*/\1/p')" + echo "stats=$(cq_quote "$(printf '%s\n' "$_cq_out" | sed -n 's/^stats: *//p')")" + _e=$(printf '%s\n' "$_cq_out" | sed -n 's/^last error: *//p') + [ "$_e" = none ] && _e= + echo "err=$(cq_quote "$_e")" + ;; + *) die "usage: csqtt on|off|state" ;; + esac +} + # --- Tailscale login -------------------------------------------------------- TS_DIR="$NIKKI_DIR/run/tailscale" @@ -1482,5 +1553,6 @@ case "${1:-}" in install) cmd_install ;; fix) cmd_fix ;; ts-login) shift; cmd_ts_login "$@" ;; + csqtt) shift; cmd_csqtt "$@" ;; *) sed -n '2,32p' "$SELF" >&2; exit 2 ;; esac