diff --git a/README.md b/README.md index bdc6b6f..fa41438 100644 --- a/README.md +++ b/README.md @@ -200,8 +200,17 @@ MagicDNS (админка Tailscale → DNS). `https://eu.bmstu.ru`) / `TS_CHECK_URL` (HTTP-сервис на ноде тейлнета, по умолчанию `http://100.69.216.50:8080`) в `common.env`. Кнопка проверки задержки этих групп в дашборде открывает его через туннель (если дашборд -берёт адрес из группы); сами по таймеру они не проверяются. Tailscale ещё проверяется -кнопкой «Проверить» на странице mihomo-kit. +берёт адрес из группы); сами по таймеру они не проверяются. На странице mihomo-kit их +открывает кнопка «Проверить» (у OpenVPN — «Проверка сайта», `bmstu-otp.sh probe`). + +OpenVPN сам ничего через туннель не проверяет. Connect таких запросов не делает, а +URL-тест виден в логах сайта, который он открывает: `HEAD /` от Go-клиента, по таймеру. +Поэтому с ядром kit состояние туннеля (подключён с такого-то времени, подключается, сервер +не принял сессию) берётся из API mihomo — ядро отдаёт его в поле `openvpn` прокси, — и +cron, LuCI («Состояние») и `bmstu-otp.sh status` не шлют ни одного запроса. Новый OTP +cron даёт, только если сервер не принял токен сессии или туннель не поднимается 5 минут +(`DOWN_GRACE`). Ядра `stock`/`official` состояние не отдают: с ними cron открывает адрес +проверки не чаще раза в 10 минут (`PROBE_EVERY`), в случайную секунду. Новый профиль = новый файл в `profiles.d/` (например `LOCATION=main` + `OPENVPN=0`), затем `mihomo-kit.sh build && mihomo-kit.sh use <имя>`. Все опции — в @@ -216,7 +225,7 @@ MagicDNS (админка Tailscale → DNS). | убрать `100.64.0.0/10`, `172.16.0.0/12` из `nikki.proxy.reserved_ip` | иначе nikki пускает Tailscale и внутренние сети BMSTU мимо mihomo | | `ts.net` в `rebind_domain` dnsmasq | иначе защита от DNS rebinding отбрасывает адреса 100.x тейлнета | | metric: `wan`/`wan6` — 10, остальные выходы (модемы, wifi-клиент) — 50, 60, … (если не заданы руками) | при живом проводе интернет идёт по проводу, модемы — запасные | -| cron `bmstu-otp.sh check` раз в минуту | поднимает OpenVPN со свежим OTP, если туннель упал и токен сессии не принят | +| cron `bmstu-otp.sh check` раз в минуту | держит туннель по расписанию/таймеру; со свежим OTP поднимает, если сервер не принял токен сессии или туннель долго лежит (состояние из ядра, без запросов через туннель) | | `bmstu-otp.sh write` в `/etc/init.d/nikki` | провайдер OpenVPN со свежим OTP перед стартом mihomo: ядро kit подключается сразу | | переустановка `libcurl4 curl`, если curl сломан | `Error relocating ... symbol not found` | diff --git a/luci/acl.json b/luci/acl.json index e9bee73..e41b4e6 100644 --- a/luci/acl.json +++ b/luci/acl.json @@ -3,7 +3,7 @@ "description": "mihomo-kit: profiles, OpenVPN, Tailscale", "read": { "ubus": { - "mihomo-kit": [ "status", "ovpn_status", "job", "update_check", "ts_check" ] + "mihomo-kit": [ "status", "ovpn_status", "ovpn_probe", "job", "update_check", "ts_check" ] } }, "write": { diff --git a/luci/mihomo-kit.js b/luci/mihomo-kit.js index 4010bf0..f489dc1 100644 --- a/luci/mihomo-kit.js +++ b/luci/mihomo-kit.js @@ -11,6 +11,7 @@ var callStatus = rpc.declare({ object: 'mihomo-kit', method: 'status', expect: { // slow calls (delay tests, the git server) go as their own requests: LuCI batches calls // made at the same moment into one request, and uhttpd runs a batch one call after another var callOvpnStatus = rpc.declare({ object: 'mihomo-kit', method: 'ovpn_status', nobatch: true, expect: { '': {} } }); +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 callTsCheck = rpc.declare({ object: 'mihomo-kit', method: 'ts_check', nobatch: true, expect: { '': {} } }); @@ -308,6 +309,7 @@ return view.extend({ if (st.openvpn) { var ovpnState = E('span', '—'); + var probeRes = E('span'); var otp = E('span', '—'); var modeNow = E('span', '—'); var modeNext = E('span', '—'); @@ -316,16 +318,23 @@ return view.extend({ var schedStart = E('input', { 'type': 'time', 'value': '09:00' }); var schedEnd = E('input', { 'type': 'time', 'value': '17:00' }); 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 var ovpnCheck = function() { - dom.content(ovpnState, E('em', 'проверяю…')); + dom.content(ovpnState, E('em', 'обновляю…')); return callOvpnStatus().then(function(o) { + var since = o.up_hm + (o.up_day == 'today' ? '' : o.up_day == 'tomorrow' ? ' завтра' : ' (' + o.up_day + ')'); dom.content(ovpnState, { - up: E('strong', { 'style': 'color:green' }, 'туннель работает, ' + o.delay + ' мс'), - down: [ E('strong', { 'style': 'color:#c00' }, 'туннель не отвечает'), ' ' + (o.message || '') ], - off: 'выключен' - }[o.state] || o.state); - if (o.url) - ovpnState.appendChild(E('span', { 'class': 'cbi-value-description' }, [ ' — ', o.url ])); + closed: 'закрыт', + up: E('strong', { 'style': 'color:green' }, 'подключён с ' + since), + connecting: [ E('strong', { 'style': 'color:#c60' }, 'подключается'), + o.err ? desc(' — ' + o.err) : '' ], + rejected: [ E('strong', { 'style': 'color:#c00' }, 'сервер не принял сессию'), + desc(' — cron возьмёт новый OTP в течение минуты') ], + unknown: [ E('strong', 'ядро не сообщает состояние'), + desc(' — с этим ядром cron проверяет туннель запросом к сайту раз в ~10 минут, ' + + 'и маскировка под Connect неполная. Нужно ядро kit («Обслуживание» → ядро).') ] + }[o.link] || o.link || '—'); dom.content(otp, o.otp ? o.otp + ' (ещё ' + o.otp_left + ' с)' : '—'); var m = ovpnMode(o); dom.content(modeNow, [ E('strong', m.now) ].concat(m.pending @@ -347,7 +356,20 @@ return view.extend({ sections.push(section('OpenVPN', [ E('table', { 'class': 'table' }, [ row('Состояние', [ ovpnState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action', - 'click': ui.createHandlerFn(this, ovpnCheck) }, 'Проверить') ]), + 'click': ui.createHandlerFn(this, ovpnCheck) }, 'Обновить') ]), + row('Проверка сайта', [ E('button', { 'class': 'btn cbi-button cbi-button-action', + 'click': ui.createHandlerFn(this, function() { + dom.content(probeRes, E('em', 'открываю…')); + return callOvpnProbe().then(function(r) { + dom.content(probeRes, [ r.state == 'up' + ? E('strong', { 'style': 'color:green' }, 'открывается, ' + r.delay + ' мс') + : [ E('strong', { 'style': 'color:#c00' }, 'не открывается'), ' ' + (r.message || '') ], + desc(' — ' + (r.url || '')) ]); + }).catch(function(e) { dom.content(probeRes, String(e)); }); + }) }, 'Проверить'), ' ', probeRes, + E('div', { 'class': 'cbi-value-description' }, + 'Открывает адрес проверки через туннель. Только по кнопке: сайт видит такой запрос в логах, ' + + 'а сам Connect их не делает. Адрес лучше взять из тех, что и так открываешь в браузере.') ]), row('OTP сейчас', otp), row('Сейчас', modeNow), row('Дальше', modeNext), @@ -636,7 +658,7 @@ return view.extend({ field('Логин', f.vpn_username), field('Пароль (без OTP)', f.vpn_password), field('TOTP-секрет', f.totp_secret), - field('Адрес для проверки', f.ovpn_check_url, 'что открывает проверка туннеля в дашборде (группа BMSTU); лучше внутренний ресурс') + field('Адрес для проверки', f.ovpn_check_url, 'что открывает ручная проверка туннеля (кнопка «Проверить» в блоке OpenVPN, тест задержки в дашборде; с ядром не из kit — ещё и cron раз в ~10 минут). Сайт видит этот запрос, поэтому лучше страница, которую и так открываешь в браузере') ]); dom.content(tsBox, [ field('Имя ноды', f.ts_hostname), diff --git a/luci/rpcd.sh b/luci/rpcd.sh index d172e11..b933d68 100644 --- a/luci/rpcd.sh +++ b/luci/rpcd.sh @@ -3,7 +3,9 @@ # # 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 +# 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) # 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 @@ -124,26 +126,29 @@ 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 's/^(mode|want|tunnel|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')" - for k in mode tunnel until_hm until_day after why next_to next_hm next_day win sched_start sched_end; do + 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' \ + -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 eval "json_add_string $k \"\${st_$k:-}\"" done - for k in want until next sched jitter; do + for k in want up_since until next sched jitter; do eval "json_add_int $k \"\${st_$k:-0}\"" done - if [ "${st_tunnel:-}" = down ]; 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 } +# 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) @@ -407,12 +412,13 @@ m_job() { 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}}' + 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}}' ;; call) case "$2" in status) m_status ;; ovpn_status) m_ovpn_status ;; + ovpn_probe) m_ovpn_probe ;; job) m_job ;; run) m_run ;; config_get) m_config_get ;; diff --git a/router/bmstu-otp.sh b/router/bmstu-otp.sh index 6b267a5..54e8ff1 100755 --- a/router/bmstu-otp.sh +++ b/router/bmstu-otp.sh @@ -10,14 +10,20 @@ # with the auth-token, and sends the server EXIT when closed; once the token is # rejected it waits for a provider with a fresh OTP (cron check). # +# No traffic of its own through the tunnel: OpenVPN Connect sends none, and a +# periodic URL test shows up in the logs of the site it opens (a HEAD from a Go +# client every minute). With the kit core the watchdog reads the tunnel state +# from the mihomo API instead; only "probe" (by hand) opens CHECK_URL. Other +# cores report no state: there the cron check probes, rarely and at random moments. +# # Usage: # bmstu-otp.sh otp print the current TOTP code # bmstu-otp.sh authfile print username/password lines (openvpn auth-user-pass file) # bmstu-otp.sh refresh regenerate provider with fresh OTP, reload, warm up # bmstu-otp.sh up bring the tunnel up if it should be up and does not answer # 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); the -# two-probe test refreshes a dead tunnel (cron, once a minute) +# 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: work-hours schedule (MSK), persisted @@ -26,7 +32,8 @@ # 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 status what decides now, the next change, whether the tunnel answers +# 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) # bmstu-otp.sh want exit code: should the tunnel be up now # bmstu-otp.sh debug show the real handshake error in the nikki log @@ -63,9 +70,17 @@ api_from_uci() { # (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}" +# 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}" # ms, must exceed HANDSHAKE_TIMEOUT (max 32767) : "${CHECK_TIMEOUT:=25000}" +# cores without the tunnel state: the cron check probes at most every PROBE_EVERY +# seconds, after a random pause of up to PROBE_SPREAD seconds +: "${PROBE_EVERY:=600}" "${PROBE_SPREAD:=45}" +# kit core: a tunnel that has not come up for this long gets a fresh OTP (it +# reconnects by itself meanwhile) +: "${DOWN_GRACE:=300}" # scrv1 - what openvpn / OpenVPN Connect send for "static-challenge ... 1" (the BMSTU # profile): SCRV1:b64(pass):b64(otp) # otp-last - (the server accepts it too) @@ -260,9 +275,50 @@ wait_api() { done } -alive() { +# HTTP check through the tunnel. The site sees it (HEAD from a Go client), so it +# runs only by hand and for cores that report no tunnel state. +probe() { api GET "/proxies/$GROUP_NAME/delay" -G \ - --data-urlencode "url=$CHECK_URL" --data-urlencode "timeout=$CHECK_TIMEOUT" >/dev/null 2>&1 + --data-urlencode "url=$CHECK_URL" --data-urlencode "timeout=$CHECK_TIMEOUT" 2>/dev/null +} + +# tunnel state from the kit core, no traffic: _cs_since (unix, 0 = down), +# _cs_failed (true once the server rejected the credentials), _cs_err (last +# connect error). Non-zero when the core reports none (stock / official core, +# OVPN_MIMIC=mihomo without auto-connect, no such proxy, API down). +core_state() { + _j=$(api GET "/providers/proxies/$PROVIDER_NAME/$PROXY_NAME" 2>/dev/null) || return 1 + [ "$(jsonfilter -s "$_j" -e '@.openvpn.auto_connect' 2>/dev/null)" = true ] || return 1 + _cs_since=$(jsonfilter -s "$_j" -e '@.openvpn.connected_since' 2>/dev/null) + _cs_failed=$(jsonfilter -s "$_j" -e '@.openvpn.auth_failed' 2>/dev/null) + _cs_err=$(jsonfilter -s "$_j" -e '@.openvpn.last_error' 2>/dev/null) + case "$_cs_since" in '' | *[!0-9]*) _cs_since=0 ;; esac + return 0 +} + +# wait_up : 0 once the kit core reports the tunnel up, 1 when it is still down +# after seconds or the credentials were rejected, 2 when the core reports no state +wait_up() { + _i=0 + while :; do + core_state || return 2 + [ "$_cs_since" -gt 0 ] && return 0 + [ "$_cs_failed" = true ] && return 1 + [ "$_i" -ge "$1" ] && return 1 + sleep 1 + _i=$((_i + 1)) + done +} + +# is the tunnel up: the core's state (allowing a handshake in progress to +# finish), or a probe for cores without it +tunnel_ok() { + wait_up "$((HANDSHAKE_TIMEOUT + 5))" + case $? in + 0) return 0 ;; + 1) return 1 ;; + esac + probe >/dev/null } # provider with a single direct proxy: the old tunnel gets closed with the @@ -300,15 +356,60 @@ refresh() { write_provider wait_api api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)" - # handshake right now, while the OTP is valid - if alive; then + rm -f "$DOWN_SINCE" + # the handshake has to happen now, while the OTP is valid: the kit core + # starts it by itself, other cores dial on the first request (the probe) + _cs_err= + if tunnel_ok; then log "tunnel is up" else - log "tunnel did not come up after refresh (check nikki log)" + log "tunnel did not come up after refresh (${_cs_err:-check nikki log})" return 1 fi } +# kit core, steady state (cron): it reconnects by itself with the session +# token. A fresh OTP is needed once the server rejected the token, or when the +# tunnel has stayed down for DOWN_GRACE seconds. +DOWN_SINCE=${DOWN_SINCE:-/tmp/bmstu-otp.down} +watch_core() { + if [ "$_cs_since" -gt 0 ]; then + rm -f "$DOWN_SINCE" + return 0 + fi + if [ "$_cs_failed" = true ]; then + log "the server rejected the session (${_cs_err:-AUTH_FAILED}), new OTP" + refresh + return + fi + _now=$(date +%s) + _d=$(cat "$DOWN_SINCE" 2>/dev/null) + case "$_d" in '' | *[!0-9]*) _d=$_now && echo "$_d" > "$DOWN_SINCE" ;; esac + [ $((_now - _d)) -ge "$DOWN_GRACE" ] || return 0 + log "tunnel down for $((_now - _d)) s (${_cs_err:-no error}), new OTP" + refresh +} + +# other cores (no tunnel state): probe CHECK_URL, but only every PROBE_EVERY +# seconds and not on the minute mark, so it does not look like a clock +PROBE_LAST=${PROBE_LAST:-/tmp/bmstu-otp.probe} +watch_probe() { + _now=$(date +%s) + _last=$(cat "$PROBE_LAST" 2>/dev/null) + case "$_last" in '' | *[!0-9]*) _last=0 ;; esac + [ $((_now - _last)) -ge "$PROBE_EVERY" ] || return 0 + echo "$_now" > "$PROBE_LAST" + sleep $(($(od -An -N2 -tu2 /dev/urandom | tr -d ' ') % (PROBE_SPREAD + 1))) + probe >/dev/null && return 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 + probe >/dev/null && return 0 + log "tunnel is down (2 failed probes), refreshing" + refresh +} + # --- schedule / timer ------------------------------------------------------- # "HH:MM" -> minutes since midnight on stdout; non-zero on a malformed value @@ -442,6 +543,10 @@ when() { # mode timer | manual | schedule | always: what decides now # want 1 when the tunnel should be up now # tunnel up | down: whether the provider holds the tunnel (not a probe) +# link closed | up | connecting | rejected | unknown: the kit core's tunnel +# state, no traffic (unknown: the core reports none) +# up_since when the tunnel came up (epoch, 0 = not up), up_hm, up_day +# err the core's last connect error, single-quoted # until timer end (epoch, 0 = none), until_hm, until_day (today|tomorrow|date) # 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 @@ -468,7 +573,31 @@ state() { fi echo "mode=$_mode" echo "want=$_want" - tunnel_is_down && echo "tunnel=down" || echo "tunnel=up" + _link=unknown _cs_since=0 + if tunnel_is_down; then + echo "tunnel=down" + _link=closed + else + echo "tunnel=up" + if core_state; then + if [ "$_cs_since" -gt 0 ]; then + _link=up + elif [ "$_cs_failed" = true ]; then + _link=rejected + else + _link=connecting + fi + # quotes and shell specials dropped: the line is eval'ed + [ -n "$_cs_err" ] && echo "err='$(printf '%s' "$_cs_err" | tr -d "'\"\`\\\\\$\n" | cut -c1-200)'" + fi + fi + echo "link=$_link" + echo "up_since=$_cs_since" + if [ "$_cs_since" -gt 0 ]; then + set -- $(when "$_cs_since") + echo "up_hm=$1" + echo "up_day=$2" + fi if [ "${OVPN_SCHED:-0}" = 1 ] && sched_next; then set -- $(when "$_next") echo "next=$_next" @@ -521,13 +650,12 @@ reconcile() { log "bringing the tunnel up" 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 - elif alive; then + if core_state; then + watch_core + else + watch_probe + fi + elif tunnel_ok; then log "tunnel is up" else refresh @@ -657,6 +785,16 @@ case "${1:-}" in reconcile ;; state) state ;; + probe) + tunnel_is_down && die "the tunnel is closed" + wait_api + if r=$(probe); then + echo "$CHECK_URL through the tunnel: $(jsonfilter -s "$r" -e '@.delay' 2>/dev/null || echo '?') ms" + else + echo "$CHECK_URL does not open through the tunnel" + exit 1 + fi + ;; status) eval "$(state)" case "$mode" in @@ -671,13 +809,13 @@ case "${1:-}" in echo "schedule: $sched_start-$sched_end MSK, today $win (jitter +-$jitter min)" [ "$mode" = schedule ] && echo "turns $next_to at $next_hm $next_day" fi - if [ "$tunnel" = down ]; then - echo "tunnel closed" - elif alive; then - echo "tunnel is up" - else - echo "tunnel does not answer (the cron check refreshes it)" - fi + case "$link" in + closed) echo "tunnel closed" ;; + up) echo "tunnel up since $up_hm $up_day" ;; + connecting) echo "tunnel connecting${err:+ (last error: $err)}" ;; + rejected) echo "the server rejected the session: the cron check gets a new OTP within a minute" ;; + *) echo "tunnel state unknown: this core does not report it (bmstu-otp.sh probe opens $CHECK_URL)" ;; + esac [ "$want" = 1 ] && [ "$tunnel" = down ] && echo "the cron check brings it up within a minute" [ "$want" = 0 ] && [ "$tunnel" = up ] && echo "the cron check takes it down within a minute" true diff --git a/tools/core/openvpn-connect-mimic.patch b/tools/core/openvpn-connect-mimic.patch index 1567928..94aaffe 100644 --- a/tools/core/openvpn-connect-mimic.patch +++ b/tools/core/openvpn-connect-mimic.patch @@ -1,8 +1,23 @@ diff --git a/adapter/outbound/openvpn.go b/adapter/outbound/openvpn.go -index 3c7b1e6..4401994 100644 +index 3c7b1e6..3c1b947 100644 --- a/adapter/outbound/openvpn.go +++ b/adapter/outbound/openvpn.go -@@ -35,6 +35,14 @@ type OpenVPN struct { +@@ -2,12 +2,14 @@ package outbound + + import ( + "context" ++ "encoding/json" + "errors" + "fmt" + "net" + "net/netip" + "os" + "sync" ++ "sync/atomic" + "time" + + "github.com/metacubex/mihomo/common/contextutils" +@@ -35,6 +37,21 @@ type OpenVPN struct { runCancel context.CancelFunc runLock *semaphore.Weighted running bool @@ -14,10 +29,17 @@ index 3c7b1e6..4401994 100644 + tokenPass string + authFailed bool + linkDown chan struct{} ++ ++ // tunnel state for the API (MarshalJSON), readable without runLock: ++ // when the current tunnel came up (unix seconds, 0 = down), whether the ++ // server rejected the credentials, and the last connect error. ++ upSince atomic.Int64 ++ rejected atomic.Bool ++ lastErr atomic.Value // string } type OpenVPNOption struct { -@@ -59,12 +67,18 @@ type OpenVPNOption struct { +@@ -59,12 +76,18 @@ type OpenVPNOption struct { Username string `proxy:"username,omitempty"` Password string `proxy:"password,omitempty"` PeerInfo map[string]string `proxy:"peer-info,omitempty"` @@ -38,7 +60,7 @@ index 3c7b1e6..4401994 100644 IPStack IPStackOption `proxy:"ip-stack,omitempty"` -@@ -117,6 +131,8 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) { +@@ -117,6 +140,8 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) { Username: option.Username, Password: option.Password, PeerInfo: option.PeerInfo, @@ -47,7 +69,7 @@ index 3c7b1e6..4401994 100644 PingInterval: time.Duration(option.Ping) * time.Second, PingRestart: time.Duration(option.PingRestart) * time.Second, TransitionWindow: transitionWindow, -@@ -152,9 +168,112 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) { +@@ -152,9 +177,115 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) { } outbound.dialer = option.NewDialer(outbound.DialOptions()) outbound.runCtx, outbound.runCancel = context.WithCancel(context.Background()) @@ -122,6 +144,9 @@ index 3c7b1e6..4401994 100644 + if o.runCtx.Err() != nil { + return + } ++ if err != nil { ++ o.lastErr.Store(err.Error()) ++ } + if errors.Is(err, errOpenVPNAuthRejected) { + log.Warnln("[OpenVPN](%s) %v", o.name, err) + return @@ -160,7 +185,36 @@ index 3c7b1e6..4401994 100644 func (o *OpenVPN) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) { tunDevice, r, err := o.run(ctx) if err != nil { -@@ -234,6 +353,22 @@ func (o *OpenVPN) IsL3Protocol(metadata *C.Metadata) bool { +@@ -223,6 +354,28 @@ func (o *OpenVPN) resolveUDP(ctx context.Context, metadata *C.Metadata, r resolv + return nil + } + ++// MarshalJSON adds the tunnel state to the proxy in the API, so a watchdog ++// can tell a live tunnel without sending traffic through it (a URL test is ++// a request no OpenVPN client makes by itself). ++func (o *OpenVPN) MarshalJSON() ([]byte, error) { ++ inner, err := o.Base.MarshalJSON() ++ if err != nil { ++ return inner, err ++ } ++ mapping := map[string]any{} ++ _ = json.Unmarshal(inner, &mapping) ++ state := map[string]any{ ++ "auto_connect": o.option.AutoConnect, ++ "connected_since": o.upSince.Load(), ++ "auth_failed": o.rejected.Load(), ++ } ++ if e, _ := o.lastErr.Load().(string); e != "" { ++ state["last_error"] = e ++ } ++ mapping["openvpn"] = state ++ return json.Marshal(mapping) ++} ++ + func (o *OpenVPN) ProxyInfo() C.ProxyInfo { + info := o.Base.ProxyInfo() + info.DialerProxy = o.option.DialerProxy +@@ -234,6 +387,22 @@ func (o *OpenVPN) IsL3Protocol(metadata *C.Metadata) bool { } func (o *OpenVPN) Close() error { @@ -183,7 +237,15 @@ index 3c7b1e6..4401994 100644 if o.runCancel != nil { o.runCancel() } -@@ -278,6 +413,9 @@ func (o *OpenVPN) run(ctx context.Context) (ipStack, resolver.Resolver, error) { +@@ -243,6 +412,7 @@ func (o *OpenVPN) Close() error { + o.client = nil + o.tunDevice = nil + o.running = false ++ o.upSince.Store(0) + o.runLock.Release(1) + + if client != nil { +@@ -278,6 +448,9 @@ func (o *OpenVPN) run(ctx context.Context) (ipStack, resolver.Resolver, error) { } return o.tunDevice, o.resolver, nil } @@ -193,7 +255,7 @@ index 3c7b1e6..4401994 100644 if o.runCtx.Err() != nil { return nil, nil, o.runCtx.Err() } -@@ -318,7 +456,17 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R +@@ -318,7 +491,17 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R if err != nil { return nil, nil, fmt.Errorf("connect OpenVPN server: %w", err) } @@ -212,7 +274,7 @@ index 3c7b1e6..4401994 100644 if err != nil { _ = packetIO.Close() return nil, nil, err -@@ -326,6 +474,14 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R +@@ -326,6 +509,15 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R push, err := client.Handshake(handshakeCtx) if err != nil { _ = client.Close() @@ -222,20 +284,23 @@ index 3c7b1e6..4401994 100644 + // waits for the user's next OTP: here a new proxy from the provider. + o.tokenUser, o.tokenPass = "", "" + o.authFailed = true ++ o.rejected.Store(true) + return nil, nil, fmt.Errorf("%w: %v", errOpenVPNAuthRejected, err) + } return nil, nil, fmt.Errorf("make OpenVPN handshake: %w", err) } log.Debugln("[OpenVPN](%s) handshake complete: prefixes=%v routes=%v peer-id=%d dns=%v redirect=%t block-ipv6=%t", o.name, push.Prefixes, push.Routes, push.PeerID, push.DNS, push.Redirect, push.BlockIPv6) -@@ -347,6 +503,7 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R +@@ -347,6 +539,9 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R o.client = client o.tunDevice = tunDevice o.running = true + o.linkDown = make(chan struct{}) ++ o.upSince.Store(time.Now().Unix()) ++ o.lastErr.Store("") if o.option.RemoteDnsResolve && len(o.dns) > 0 && o.resolver == nil { nss := append([]dns.NameServer(nil), o.dns...) for i := range nss { -@@ -393,6 +550,7 @@ func (o *OpenVPN) startPacketLoops() { +@@ -393,6 +588,7 @@ func (o *OpenVPN) startPacketLoops() { runCtx, runCancel := context.WithCancel(o.runCtx) client := o.client tunDevice := o.tunDevice @@ -243,18 +308,67 @@ index 3c7b1e6..4401994 100644 var stopOnce sync.Once stop := func() { stopOnce.Do(func() { -@@ -405,7 +563,11 @@ func (o *OpenVPN) startPacketLoops() { +@@ -404,8 +600,13 @@ func (o *OpenVPN) startPacketLoops() { + o.client = nil o.tunDevice = nil o.running = false - } ++ o.upSince.Store(0) ++ } + if user, pass, ok := client.AuthToken(); ok { + o.tokenUser, o.tokenPass = user, pass -+ } + } o.runLock.Release(1) + close(linkDown) }) } go func() { +diff --git a/adapter/outbound/openvpn_state_test.go b/adapter/outbound/openvpn_state_test.go +new file mode 100644 +index 0000000..078fb12 +--- /dev/null ++++ b/adapter/outbound/openvpn_state_test.go +@@ -0,0 +1,41 @@ ++package outbound ++ ++import ( ++ "encoding/json" ++ "testing" ++ ++ C "github.com/metacubex/mihomo/constant" ++) ++ ++func TestOpenVPNStateJSON(t *testing.T) { ++ o := &OpenVPN{Base: &Base{name: "bmstu-ovpn", tp: C.OpenVPN}, option: &OpenVPNOption{AutoConnect: true}} ++ o.upSince.Store(1760000000) ++ o.lastErr.Store("dial timeout") ++ o.rejected.Store(true) ++ raw, err := o.MarshalJSON() ++ if err != nil { ++ t.Fatal(err) ++ } ++ var got struct { ++ Type string `json:"type"` ++ OpenVPN struct { ++ AutoConnect bool `json:"auto_connect"` ++ ConnectedSince int64 `json:"connected_since"` ++ AuthFailed bool `json:"auth_failed"` ++ LastError string `json:"last_error"` ++ } `json:"openvpn"` ++ } ++ if err := json.Unmarshal(raw, &got); err != nil { ++ t.Fatal(err) ++ } ++ if got.Type != "OpenVPN" || !got.OpenVPN.AutoConnect || got.OpenVPN.ConnectedSince != 1760000000 || ++ !got.OpenVPN.AuthFailed || got.OpenVPN.LastError != "dial timeout" { ++ t.Fatalf("got %s", raw) ++ } ++ // through the wrapper the API serializes ++ p := NewAutoCloseProxyAdapter(o) ++ raw2, _ := p.MarshalJSON() ++ if string(raw2) != string(raw) { ++ t.Fatalf("wrapper hides the state: %s", raw2) ++ } ++} diff --git a/adapter/provider/provider.go b/adapter/provider/provider.go index fa7d56b..c472539 100644 --- a/adapter/provider/provider.go