Added ovpn reconnect pause with jitter, core ts5, core retry in auto-update
This commit is contained in:
parent
594cc29d63
commit
8b0076ea15
41
README.md
41
README.md
@ -54,8 +54,11 @@ TOTP-секрет), Tailscale; «Сохранить и применить» со
|
|||||||
Автообновление — «Включить автообновление» там же (или `mihomo-kit.sh auto-update on|off`):
|
Автообновление — «Включить автообновление» там же (или `mihomo-kit.sh auto-update on|off`):
|
||||||
cron каждый день в 4:00 по времени роутера (часовой пояс — Система → Система) проверяет
|
cron каждый день в 4:00 по времени роутера (часовой пояс — Система → Система) проверяет
|
||||||
коммит на сервере; если он новее — скачивает kit, пересобирает профили, при смене версии
|
коммит на сервере; если он новее — скачивает kit, пересобирает профили, при смене версии
|
||||||
ядра делает `fix` и перезапускает текущий профиль. Журнал — `/etc/nikki/kit/auto-update.log`,
|
ядра делает `fix` и перезапускает текущий профиль. Если kit уже свежий, а ядро не то, что он
|
||||||
последняя строка видна на странице.
|
просит (релиз ядра выложен позже кита, скачивание не удалось), автообновление ставит ядро
|
||||||
|
заново — только когда файл ядра доступен, чтобы не перезапускать nikki каждую ночь впустую.
|
||||||
|
Явный `MIHOMO_VERSION=…` в `kit.env` закрепляет ядро, и тогда оно не обновляется. Журнал —
|
||||||
|
`/etc/nikki/kit/auto-update.log`, последняя строка видна на странице.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
mihomo-kit.sh use whitelist # попал на белые списки
|
mihomo-kit.sh use whitelist # попал на белые списки
|
||||||
@ -124,11 +127,23 @@ mihomo представляется сам (`IV_VER=mihomo-openvpn`, `IV_PROTO=2
|
|||||||
- `ping 60`, `ping-restart 300` — то, что присылает сервер;
|
- `ping 60`, `ping-restart 300` — то, что присылает сервер;
|
||||||
- туннель держится всё время, как у Connect (`auto-connect` у прокси). Он поднимается сразу
|
- туннель держится всё время, как у Connect (`auto-connect` у прокси). Он поднимается сразу
|
||||||
при загрузке провайдера, без ожидания трафика: init-скрипт nikki перед стартом mihomo
|
при загрузке провайдера, без ожидания трафика: init-скрипт nikki перед стартом mihomo
|
||||||
пишет провайдер со свежим OTP (`bmstu-otp.sh write`). После обрыва ядро через 2 с
|
пишет провайдер со свежим OTP (`bmstu-otp.sh write`). После обрыва ядро переподключается
|
||||||
переподключается само, с auth-token сессии вместо пароля и OTP; если не вышло, пауза
|
само, с auth-token сессии вместо пароля и OTP. Если сервер токен не принял (AUTH_FAILED),
|
||||||
удваивается до минуты, чтобы недоступный сервер не забивал лог. Если сервер токен не
|
ядро больше не пробует — как Connect, который тогда просит новый OTP, — и туннель
|
||||||
принял (AUTH_FAILED), ядро больше не пробует — как Connect, который тогда просит новый
|
поднимает cron (`bmstu-otp.sh check`) со свежим OTP;
|
||||||
OTP, — и туннель поднимает cron (`bmstu-otp.sh check`) со свежим OTP;
|
- быстрых переподключений нет: на моментальный реконнект после обрыва или кика сервер
|
||||||
|
отвечает блокировкой учётки. После любого обрыва (в том числе молчаливого), неудачной
|
||||||
|
попытки или отказа в авторизации ядро ждёт `OVPN_RECONNECT_PAUSE` секунд (по умолчанию
|
||||||
|
120). Пауза удваивается, пока попытки не удаются или туннель падает раньше чем через 5
|
||||||
|
минут после подъёма, но не больше 10 минут. Если сессию закрыл сам сервер (RESTART/HALT —
|
||||||
|
например, админ кикнул клиента), пауза своя — `OVPN_KICK_PAUSE` (по умолчанию как
|
||||||
|
`OVPN_RECONNECT_PAUSE`). Она удваивается за каждый кик подряд, до 30 минут; сессия,
|
||||||
|
продержавшаяся 30 минут, сбрасывает счёт. К каждой паузе добавляется случайный разброс
|
||||||
|
±`OVPN_RECONNECT_JITTER` секунд (по умолчанию 30), чтобы попытки не шли по часам. Пауза
|
||||||
|
переживает перезагрузку провайдера и конфига, и трафик в BMSTU в это время туннель не
|
||||||
|
поднимает. Новый OTP cron в паузе не берёт, кнопки LuCI тоже не переподключают; в
|
||||||
|
«Состоянии» видны причина (оборвался, не подключился, сервер отключил) и время следующей
|
||||||
|
попытки;
|
||||||
- при закрытии (`off`, перезапуск nikki, новый провайдер) сервер получает EXIT
|
- при закрытии (`off`, перезапуск nikki, новый провайдер) сервер получает EXIT
|
||||||
(`cc-exit`) и сразу освобождает сессию.
|
(`cc-exit`) и сразу освобождает сессию.
|
||||||
|
|
||||||
@ -255,7 +270,7 @@ cron даёт, только если сервер не принял токен
|
|||||||
|
|
||||||
| Фикс | Зачем |
|
| Фикс | Зачем |
|
||||||
|---|---|
|
|---|---|
|
||||||
| ядро kit `v1.19.32-ts4` вместо ядра из пакета | в v1.19.29 OpenVPN не проходит рукопожатие; Tailscale через `dialer-proxy` и маскировка OpenVPN — только в ядре kit |
|
| ядро kit `v1.19.32-ts5` вместо ядра из пакета | в v1.19.29 OpenVPN не проходит рукопожатие; Tailscale через `dialer-proxy` и маскировка OpenVPN — только в ядре kit |
|
||||||
| `TS_FORCE_NOISE_443=true` в `/etc/init.d/nikki` | провайдер ломает control-соединение Tailscale на порту 80, вход зависает |
|
| `TS_FORCE_NOISE_443=true` в `/etc/init.d/nikki` | провайдер ломает control-соединение Tailscale на порту 80, вход зависает |
|
||||||
| убрать `100.64.0.0/10`, `172.16.0.0/12` из `nikki.proxy.reserved_ip` | иначе nikki пускает Tailscale и внутренние сети BMSTU мимо mihomo |
|
| убрать `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 тейлнета |
|
| `ts.net` в `rebind_domain` dnsmasq | иначе защита от DNS rebinding отбрасывает адреса 100.x тейлнета |
|
||||||
@ -307,7 +322,7 @@ RU-адреса, без OpenVPN, Tailscale, торрентов и `PUSH`; сво
|
|||||||
он открывает UDP-сокет без адреса назначения, и любой прокси mihomo падает на его
|
он открывает UDP-сокет без адреса назначения, и любой прокси mihomo падает на его
|
||||||
резолве (`magicsock: Rebind IPv4 failed: failed to bind any ports`,
|
резолве (`magicsock: Rebind IPv4 failed: failed to bind any ports`,
|
||||||
[MetaCubeX/mihomo#3142](https://github.com/MetaCubeX/mihomo/issues/3142)). Поэтому kit
|
[MetaCubeX/mihomo#3142](https://github.com/MetaCubeX/mihomo/issues/3142)). Поэтому kit
|
||||||
ставит своё ядро `v1.19.32-ts4` — официальный v1.19.32 с правкой
|
ставит своё ядро `v1.19.32-ts5` — официальный v1.19.32 с правкой
|
||||||
`tools/core/tailscale-packet-listener.patch`: UDP-сокет открывается на роутере, а
|
`tools/core/tailscale-packet-listener.patch`: UDP-сокет открывается на роутере, а
|
||||||
control-сервер и DERP идут по TCP через `dialer-proxy`. На белых списках прямой UDP не
|
control-сервер и DERP идут по TCP через `dialer-proxy`. На белых списках прямой UDP не
|
||||||
проходит, и Tailscale работает через DERP — медленнее прямого соединения, но работает.
|
проходит, и Tailscale работает через DERP — медленнее прямого соединения, но работает.
|
||||||
@ -408,10 +423,10 @@ tests/fixtures/ профили для test.sh (фиктивные секре
|
|||||||
Официальный mihomo плюс правки из `tools/core/*.patch` (Tailscale через `dialer-proxy`,
|
Официальный mihomo плюс правки из `tools/core/*.patch` (Tailscale через `dialer-proxy`,
|
||||||
маскировка OpenVPN). Нужны git и Go.
|
маскировка OpenVPN). Нужны git и Go.
|
||||||
|
|
||||||
1. `tools/core/build.sh v1.19.32 ts4` — клонирует mihomo `v1.19.32`, накладывает патчи и
|
1. `tools/core/build.sh v1.19.32 ts5` — клонирует mihomo `v1.19.32`, накладывает патчи и
|
||||||
собирает `tools/core/dist/mihomo-linux-<arch>-v1.19.32-ts4.gz` для arm64, amd64, armv7,
|
собирает `tools/core/dist/mihomo-linux-<arch>-v1.19.32-ts5.gz` для arm64, amd64, armv7,
|
||||||
mips-softfloat, mipsle-softfloat.
|
mips-softfloat, mipsle-softfloat.
|
||||||
2. В репозитории kit создать релиз с тегом `core-v1.19.32-ts4` и приложить все `.gz`, не
|
2. В репозитории kit создать релиз с тегом `core-v1.19.32-ts5` и приложить все `.gz`, не
|
||||||
переименовывая: роутер качает `$MIHOMO_BASE/mihomo-linux-<arch>-<версия>.gz`.
|
переименовывая: роутер качает `$MIHOMO_BASE/mihomo-linux-<arch>-<версия>.gz`.
|
||||||
3. `CORE_KIT` в `router/mihomo-kit.sh` — та же версия. Пушить кит только после релиза:
|
3. `CORE_KIT` в `router/mihomo-kit.sh` — та же версия. Пушить кит только после релиза:
|
||||||
роутеры берут кит из `main` и иначе не найдут ядро.
|
роутеры берут кит из `main` и иначе не найдут ядро.
|
||||||
@ -420,7 +435,7 @@ tests/fixtures/ профили для test.sh (фиктивные секре
|
|||||||
`bmstu-otp.sh refresh` (провайдер OpenVPN с новыми полями). Проверить:
|
`bmstu-otp.sh refresh` (провайдер OpenVPN с новыми полями). Проверить:
|
||||||
`mihomo-kit.sh core-info`, `bmstu-otp.sh status`.
|
`mihomo-kit.sh core-info`, `bmstu-otp.sh status`.
|
||||||
|
|
||||||
Новая версия mihomo или новая правка — следующий суффикс (`ts5`) в шагах 1–3. Патчи
|
Новая версия mihomo или новая правка — следующий суффикс (`ts6`) в шагах 1–3. Патчи
|
||||||
применяются по алфавиту; если не накладываются, поправить их на новом теге.
|
применяются по алфавиту; если не накладываются, поправить их на новом теге.
|
||||||
|
|
||||||
После правки шаблонов или движка:
|
После правки шаблонов или движка:
|
||||||
|
|||||||
@ -344,7 +344,15 @@ return view.extend({
|
|||||||
connecting: [ E('strong', { 'style': 'color:#c60' }, 'подключается'),
|
connecting: [ E('strong', { 'style': 'color:#c60' }, 'подключается'),
|
||||||
o.err ? desc(' — ' + o.err) : '' ],
|
o.err ? desc(' — ' + o.err) : '' ],
|
||||||
rejected: [ E('strong', { 'style': 'color:#c00' }, 'сервер не принял сессию'),
|
rejected: [ E('strong', { 'style': 'color:#c00' }, 'сервер не принял сессию'),
|
||||||
desc(' — cron возьмёт новый OTP в течение минуты') ],
|
desc(o.retry_hm ? ' — cron возьмёт новый OTP после паузы, в ' + o.retry_hm
|
||||||
|
: ' — cron возьмёт новый OTP в течение минуты') ],
|
||||||
|
held: [ E('strong', { 'style': 'color:#c60' }, {
|
||||||
|
kick: 'сервер отключил сессию',
|
||||||
|
drop: 'туннель оборвался',
|
||||||
|
failed: 'не подключился'
|
||||||
|
}[o.retry_why] || 'пауза'),
|
||||||
|
desc(' — следующая попытка в ' + o.retry_hm + ' (без быстрых переподключений)' +
|
||||||
|
(o.err ? '; ' + o.err : '')) ],
|
||||||
unknown: [ E('strong', 'ядро не сообщает состояние'),
|
unknown: [ E('strong', 'ядро не сообщает состояние'),
|
||||||
desc(' — с этим ядром cron проверяет туннель запросом к сайту раз в ~10 минут, ' +
|
desc(' — с этим ядром cron проверяет туннель запросом к сайту раз в ~10 минут, ' +
|
||||||
'и маскировка под Connect неполная. Нужно ядро kit («Обслуживание» → ядро).') ]
|
'и маскировка под Connect неполная. Нужно ядро kit («Обслуживание» → ядро).') ]
|
||||||
|
|||||||
@ -132,9 +132,9 @@ m_ovpn_status() {
|
|||||||
# what decides the tunnel now and the next change (bmstu-otp.sh state); only
|
# what decides the tunnel now and the next change (bmstu-otp.sh state); only
|
||||||
# known keys with plain values get through to eval
|
# known keys with plain values get through to eval
|
||||||
eval "$(bmstu-otp.sh state 2>/dev/null |
|
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|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_start|sched_end|sched_days|jitter)=([A-Za-z0-9:._-]*)$/st_\1=\2/p' \
|
||||||
-e "s/^err='([^'\`\$\\\\]*)'\$/st_err='\\1'/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 sched_days; do
|
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:-}\""
|
eval "json_add_string $k \"\${st_$k:-}\""
|
||||||
done
|
done
|
||||||
for k in want up_since until next sched jitter; do
|
for k in want up_since until next sched jitter; do
|
||||||
|
|||||||
@ -85,6 +85,15 @@ api_from_uci() {
|
|||||||
# kit core: a tunnel that has not come up for this long gets a fresh OTP (it
|
# kit core: a tunnel that has not come up for this long gets a fresh OTP (it
|
||||||
# reconnects by itself meanwhile)
|
# reconnects by itself meanwhile)
|
||||||
: "${DOWN_GRACE:=300}"
|
: "${DOWN_GRACE:=300}"
|
||||||
|
# kit core: no quick reconnects, a quick reconnect into a drop or a kick gets the
|
||||||
|
# account blocked. After the tunnel went down, a failed connect or rejected
|
||||||
|
# credentials the core waits OVPN_RECONNECT_PAUSE seconds, doubled while attempts
|
||||||
|
# fail or tunnels drop within 5 min (up to 10 min); after the server ended the
|
||||||
|
# session itself (RESTART/HALT, an admin's kick) OVPN_KICK_PAUSE, doubled for each
|
||||||
|
# kick in a row (up to 30 min). Each pause +-OVPN_RECONNECT_JITTER seconds at random.
|
||||||
|
# No fresh OTP during a pause either.
|
||||||
|
: "${OVPN_RECONNECT_PAUSE:=120}" "${OVPN_RECONNECT_JITTER:=30}"
|
||||||
|
: "${OVPN_KICK_PAUSE:=$OVPN_RECONNECT_PAUSE}"
|
||||||
# scrv1 - what openvpn / OpenVPN Connect send for "static-challenge ... 1" (the BMSTU
|
# scrv1 - what openvpn / OpenVPN Connect send for "static-challenge ... 1" (the BMSTU
|
||||||
# profile): SCRV1:b64(pass):b64(otp)
|
# profile): SCRV1:b64(pass):b64(otp)
|
||||||
# otp-last - <password><otp> (the server accepts it too)
|
# otp-last - <password><otp> (the server accepts it too)
|
||||||
@ -196,6 +205,9 @@ mimic_connect_mac() {
|
|||||||
echo " options-string: \"V4,dev-type tun,link-mtu $mtu,tun-mtu 1500,proto $p,cipher BF-CBC,auth SHA1,keysize 128,key-method 2,tls-client\""
|
echo " options-string: \"V4,dev-type tun,link-mtu $mtu,tun-mtu 1500,proto $p,cipher BF-CBC,auth SHA1,keysize 128,key-method 2,tls-client\""
|
||||||
# up right away, reconnect with the auth-token, EXIT on close (kit core)
|
# up right away, reconnect with the auth-token, EXIT on close (kit core)
|
||||||
echo " auto-connect: true"
|
echo " auto-connect: true"
|
||||||
|
echo " reconnect-pause: $OVPN_RECONNECT_PAUSE"
|
||||||
|
echo " reconnect-jitter: $OVPN_RECONNECT_JITTER"
|
||||||
|
echo " kick-pause: $OVPN_KICK_PAUSE"
|
||||||
echo " peer-info-raw: |"
|
echo " peer-info-raw: |"
|
||||||
for l in IV_VER=3.11.1 IV_PLAT=mac IV_NCP=2 IV_TCPNL=1 IV_PROTO=8094 IV_MTU=1600 \
|
for l in IV_VER=3.11.1 IV_PLAT=mac IV_NCP=2 IV_TCPNL=1 IV_PROTO=8094 IV_MTU=1600 \
|
||||||
IV_CIPHERS=AES-128-CBC:AES-192-CBC:AES-256-CBC:AES-128-GCM:AES-192-GCM:AES-256-GCM:CHACHA20-POLY1305 \
|
IV_CIPHERS=AES-128-CBC:AES-192-CBC:AES-256-CBC:AES-128-GCM:AES-192-GCM:AES-256-GCM:CHACHA20-POLY1305 \
|
||||||
@ -288,7 +300,8 @@ probe() {
|
|||||||
|
|
||||||
# tunnel state from the kit core, no traffic: _cs_since (unix, 0 = down),
|
# 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
|
# _cs_failed (true once the server rejected the credentials), _cs_err (last
|
||||||
# connect error). Non-zero when the core reports none (stock / official core,
|
# connect error), _cs_retry (unix: reconnect pause, no attempt before then;
|
||||||
|
# 0 = none) and _cs_why (why the pause: drop | kick | failed | rejected). Non-zero when the core reports none (stock / official core,
|
||||||
# OVPN_MIMIC=mihomo without auto-connect, no such proxy, API down).
|
# OVPN_MIMIC=mihomo without auto-connect, no such proxy, API down).
|
||||||
core_state() {
|
core_state() {
|
||||||
_j=$(api GET "/providers/proxies/$PROVIDER_NAME/$PROXY_NAME" 2>/dev/null) || return 1
|
_j=$(api GET "/providers/proxies/$PROVIDER_NAME/$PROXY_NAME" 2>/dev/null) || return 1
|
||||||
@ -296,7 +309,10 @@ core_state() {
|
|||||||
_cs_since=$(jsonfilter -s "$_j" -e '@.openvpn.connected_since' 2>/dev/null)
|
_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_failed=$(jsonfilter -s "$_j" -e '@.openvpn.auth_failed' 2>/dev/null)
|
||||||
_cs_err=$(jsonfilter -s "$_j" -e '@.openvpn.last_error' 2>/dev/null)
|
_cs_err=$(jsonfilter -s "$_j" -e '@.openvpn.last_error' 2>/dev/null)
|
||||||
|
_cs_retry=$(jsonfilter -s "$_j" -e '@.openvpn.retry_at' 2>/dev/null)
|
||||||
|
_cs_why=$(jsonfilter -s "$_j" -e '@.openvpn.retry_why' 2>/dev/null)
|
||||||
case "$_cs_since" in '' | *[!0-9]*) _cs_since=0 ;; esac
|
case "$_cs_since" in '' | *[!0-9]*) _cs_since=0 ;; esac
|
||||||
|
case "$_cs_retry" in '' | *[!0-9]*) _cs_retry=0 ;; esac
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -308,6 +324,7 @@ wait_up() {
|
|||||||
core_state || return 2
|
core_state || return 2
|
||||||
[ "$_cs_since" -gt 0 ] && return 0
|
[ "$_cs_since" -gt 0 ] && return 0
|
||||||
[ "$_cs_failed" = true ] && return 1
|
[ "$_cs_failed" = true ] && return 1
|
||||||
|
[ "$_cs_retry" -gt "$(date +%s)" ] && return 1
|
||||||
[ "$_i" -ge "$1" ] && return 1
|
[ "$_i" -ge "$1" ] && return 1
|
||||||
sleep 1
|
sleep 1
|
||||||
_i=$((_i + 1))
|
_i=$((_i + 1))
|
||||||
@ -356,7 +373,17 @@ routes_set() {
|
|||||||
log "warning: routes reload failed (API $API), applies on the next nikki restart"
|
log "warning: routes reload failed (API $API), applies on the next nikki restart"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# reconnect pause: no new provider (its OTP would be stale by the end of the
|
||||||
|
# pause, and a new proxy waits for it all the same)
|
||||||
|
pause_held() {
|
||||||
|
core_state && [ "$_cs_retry" -gt "$(date +%s)" ]
|
||||||
|
}
|
||||||
|
|
||||||
refresh() {
|
refresh() {
|
||||||
|
if pause_held; then
|
||||||
|
log "reconnect pause ($_cs_why${_cs_err:+: $_cs_err}), no attempt before $(date -d "@$_cs_retry" '+%H:%M:%S')"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
write_provider
|
write_provider
|
||||||
wait_api
|
wait_api
|
||||||
api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)"
|
api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)"
|
||||||
@ -381,6 +408,12 @@ watch_core() {
|
|||||||
rm -f "$DOWN_SINCE"
|
rm -f "$DOWN_SINCE"
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
|
# reconnect pause: the core waits it out by itself (a rejected session gets
|
||||||
|
# its new OTP after it), and the down grace counts from its end
|
||||||
|
if [ "$_cs_retry" -gt "$(date +%s)" ]; then
|
||||||
|
echo "$_cs_retry" > "$DOWN_SINCE"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
if [ "$_cs_failed" = true ]; then
|
if [ "$_cs_failed" = true ]; then
|
||||||
log "the server rejected the session (${_cs_err:-AUTH_FAILED}), new OTP"
|
log "the server rejected the session (${_cs_err:-AUTH_FAILED}), new OTP"
|
||||||
refresh
|
refresh
|
||||||
@ -588,8 +621,9 @@ when() {
|
|||||||
# mode timer | manual | schedule | always: what decides now
|
# mode timer | manual | schedule | always: what decides now
|
||||||
# want 1 when the tunnel should be up now
|
# want 1 when the tunnel should be up now
|
||||||
# tunnel up | down: whether the provider holds the tunnel (not a probe)
|
# tunnel up | down: whether the provider holds the tunnel (not a probe)
|
||||||
# link closed | up | connecting | rejected | unknown: the kit core's tunnel
|
# link closed | up | connecting | rejected | held | unknown: the kit core's tunnel
|
||||||
# state, no traffic (unknown: the core reports none)
|
# state, no traffic (held: reconnect pause; unknown: the core reports none)
|
||||||
|
# retry_hm end of the reconnect pause, retry_why drop | kick | failed | rejected
|
||||||
# up_since when the tunnel came up (epoch, 0 = not up), up_hm, up_day
|
# up_since when the tunnel came up (epoch, 0 = not up), up_hm, up_day
|
||||||
# err the core's last connect error, single-quoted
|
# err the core's last connect error, single-quoted
|
||||||
# until timer end (epoch, 0 = none), until_hm, until_day (today|tomorrow|date)
|
# until timer end (epoch, 0 = none), until_hm, until_day (today|tomorrow|date)
|
||||||
@ -618,7 +652,7 @@ state() {
|
|||||||
fi
|
fi
|
||||||
echo "mode=$_mode"
|
echo "mode=$_mode"
|
||||||
echo "want=$_want"
|
echo "want=$_want"
|
||||||
_link=unknown _cs_since=0
|
_link=unknown _cs_since=0 _cs_retry=0
|
||||||
if tunnel_is_down; then
|
if tunnel_is_down; then
|
||||||
echo "tunnel=down"
|
echo "tunnel=down"
|
||||||
_link=closed
|
_link=closed
|
||||||
@ -629,9 +663,16 @@ state() {
|
|||||||
_link=up
|
_link=up
|
||||||
elif [ "$_cs_failed" = true ]; then
|
elif [ "$_cs_failed" = true ]; then
|
||||||
_link=rejected
|
_link=rejected
|
||||||
|
elif [ "$_cs_retry" -gt "$(date +%s)" ]; then
|
||||||
|
_link=held
|
||||||
else
|
else
|
||||||
_link=connecting
|
_link=connecting
|
||||||
fi
|
fi
|
||||||
|
if [ "$_cs_since" -eq 0 ] && [ "$_cs_retry" -gt "$(date +%s)" ]; then
|
||||||
|
set -- $(when "$_cs_retry")
|
||||||
|
echo "retry_hm=$1"
|
||||||
|
echo "retry_why=$_cs_why"
|
||||||
|
fi
|
||||||
# quotes and shell specials dropped: the line is eval'ed
|
# 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)'"
|
[ -n "$_cs_err" ] && echo "err='$(printf '%s' "$_cs_err" | tr -d "'\"\`\\\\\$\n" | cut -c1-200)'"
|
||||||
fi
|
fi
|
||||||
@ -868,7 +909,8 @@ case "${1:-}" in
|
|||||||
closed) echo "tunnel closed" ;;
|
closed) echo "tunnel closed" ;;
|
||||||
up) echo "tunnel up since $up_hm $up_day" ;;
|
up) echo "tunnel up since $up_hm $up_day" ;;
|
||||||
connecting) echo "tunnel connecting${err:+ (last error: $err)}" ;;
|
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" ;;
|
rejected) echo "the server rejected the session: the cron check gets a new OTP${retry_hm:+ after the pause, at $retry_hm}" ;;
|
||||||
|
held) echo "reconnect pause ($retry_why${err:+: $err}): next attempt at $retry_hm" ;;
|
||||||
*) echo "tunnel state unknown: this core does not report it (bmstu-otp.sh probe opens $CHECK_URL)" ;;
|
*) echo "tunnel state unknown: this core does not report it (bmstu-otp.sh probe opens $CHECK_URL)" ;;
|
||||||
esac
|
esac
|
||||||
[ "$want" = 1 ] && [ "$tunnel" = down ] && echo "the cron check brings it up within a minute"
|
[ "$want" = 1 ] && [ "$tunnel" = down ] && echo "the cron check brings it up within a minute"
|
||||||
|
|||||||
@ -7,6 +7,12 @@ TOTP_SECRET="XXXXXXXXXXXXXXXX"
|
|||||||
#PASS_FORMAT=scrv1
|
#PASS_FORMAT=scrv1
|
||||||
# connect-mac (default: present as OpenVPN Connect 3.7.1 for macOS) | mihomo
|
# connect-mac (default: present as OpenVPN Connect 3.7.1 for macOS) | mihomo
|
||||||
#OVPN_MIMIC=connect-mac
|
#OVPN_MIMIC=connect-mac
|
||||||
|
# kit core, pauses before reconnecting (seconds): after a drop or a failed connect
|
||||||
|
# (doubled while it keeps failing, up to 10 min), after the server ended the session
|
||||||
|
# (a kick; doubled per kick in a row, up to 30 min), and the random spread of each
|
||||||
|
#OVPN_RECONNECT_PAUSE=120
|
||||||
|
#OVPN_KICK_PAUSE=120
|
||||||
|
#OVPN_RECONNECT_JITTER=30
|
||||||
|
|
||||||
# nikki API: read from uci (nikki.mixin.api_listen / api_secret) unless set here
|
# nikki API: read from uci (nikki.mixin.api_listen / api_secret) unless set here
|
||||||
#API="http://192.168.1.1:9090"
|
#API="http://192.168.1.1:9090"
|
||||||
|
|||||||
@ -48,7 +48,7 @@ PROFILES_OUT="$NIKKI_DIR/profiles"
|
|||||||
# OpenVPN presenting as OpenVPN Connect)
|
# OpenVPN presenting as OpenVPN Connect)
|
||||||
# An explicit MIHOMO_VERSION in kit.env wins (e.g. MIHOMO_VERSION=v1.19.29).
|
# An explicit MIHOMO_VERSION in kit.env wins (e.g. MIHOMO_VERSION=v1.19.29).
|
||||||
CORE_OFFICIAL=v1.19.32
|
CORE_OFFICIAL=v1.19.32
|
||||||
CORE_KIT=v1.19.32-ts4
|
CORE_KIT=v1.19.32-ts5
|
||||||
STOCK_CORE=/usr/libexec/mihomo
|
STOCK_CORE=/usr/libexec/mihomo
|
||||||
KIT_ENV=${KIT_ENV:-/etc/nikki/kit.env}
|
KIT_ENV=${KIT_ENV:-/etc/nikki/kit.env}
|
||||||
[ -f "$KIT_ENV" ] && . "$KIT_ENV"
|
[ -f "$KIT_ENV" ] && . "$KIT_ENV"
|
||||||
@ -913,6 +913,29 @@ core_ok() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# download URL of the wanted core for this router's arch; non-zero for an unknown arch
|
||||||
|
core_url() {
|
||||||
|
case "$(uname -m)" in
|
||||||
|
aarch64) _arch=arm64 ;;
|
||||||
|
x86_64) _arch=amd64 ;;
|
||||||
|
armv7l) _arch=armv7 ;;
|
||||||
|
mips) _arch=mips-softfloat ;;
|
||||||
|
mipsel | mipsle) _arch=mipsle-softfloat ;;
|
||||||
|
*) return 1 ;;
|
||||||
|
esac
|
||||||
|
echo "$MIHOMO_BASE/mihomo-linux-$_arch-$MIHOMO_VERSION.gz"
|
||||||
|
}
|
||||||
|
|
||||||
|
# can the wanted core be installed now: the package core is there, or the
|
||||||
|
# download answers (first byte only)
|
||||||
|
core_available() {
|
||||||
|
if [ "$MIHOMO_VERSION" = stock ]; then
|
||||||
|
[ -x "$STOCK_CORE" ]
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
_url=$(core_url) && curl -fsL -r 0-0 -m 30 -o /dev/null "$_url"
|
||||||
|
}
|
||||||
|
|
||||||
# Core change in two steps around the nikki restart (cmd_fix): core_fetch while
|
# Core change in two steps around the nikki restart (cmd_fix): core_fetch while
|
||||||
# nikki still runs - the router may reach the download host only through mihomo -
|
# nikki still runs - the router may reach the download host only through mihomo -
|
||||||
# then core_install with nikki stopped. CORE_PENDING: "" (nothing), stock or new.
|
# then core_install with nikki stopped. CORE_PENDING: "" (nothing), stock or new.
|
||||||
@ -931,18 +954,10 @@ core_fetch() {
|
|||||||
CORE_PENDING=stock
|
CORE_PENDING=stock
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
case "$(uname -m)" in
|
url=$(core_url) || {
|
||||||
aarch64) arch=arm64 ;;
|
|
||||||
x86_64) arch=amd64 ;;
|
|
||||||
armv7l) arch=armv7 ;;
|
|
||||||
mips) arch=mips-softfloat ;;
|
|
||||||
mipsel | mipsle) arch=mipsle-softfloat ;;
|
|
||||||
*)
|
|
||||||
log "warning: unknown arch $(uname -m), set the core manually"
|
log "warning: unknown arch $(uname -m), set the core manually"
|
||||||
return 1
|
return 1
|
||||||
;;
|
}
|
||||||
esac
|
|
||||||
url="$MIHOMO_BASE/mihomo-linux-$arch-$MIHOMO_VERSION.gz"
|
|
||||||
log "updating mihomo core ${cur:-none} -> $MIHOMO_VERSION"
|
log "updating mihomo core ${cur:-none} -> $MIHOMO_VERSION"
|
||||||
# Streamed straight next to the binary: /tmp is RAM, and the unpacked core
|
# Streamed straight next to the binary: /tmp is RAM, and the unpacked core
|
||||||
# (~56 MB) plus the .gz do not fit on small routers. No .bak copy either (flash
|
# (~56 MB) plus the .gz do not fit on small routers. No .bak copy either (flash
|
||||||
@ -1699,6 +1714,7 @@ cmd_post_update() {
|
|||||||
fi
|
fi
|
||||||
# a new kit may pin another core version
|
# a new kit may pin another core version
|
||||||
core_ok || cmd_fix
|
core_ok || cmd_fix
|
||||||
|
core_ok || auto_log "core $MIHOMO_VERSION not installed yet, retried at the next auto-update"
|
||||||
[ -f "$PROFILES_OUT/$cur.yaml" ] && cmd_use "$cur"
|
[ -f "$PROFILES_OUT/$cur.yaml" ] && cmd_use "$cur"
|
||||||
auto_log "updated to $(cut -d' ' -f1 "$KIT_DIR/VERSION"), profile $cur restarted"
|
auto_log "updated to $(cut -d' ' -f1 "$KIT_DIR/VERSION"), profile $cur restarted"
|
||||||
}
|
}
|
||||||
@ -1733,7 +1749,18 @@ cmd_auto_update() {
|
|||||||
_new=$(echo "$_out" | sed -n 's/^latest //p')
|
_new=$(echo "$_out" | sed -n 's/^latest //p')
|
||||||
case "$_cur" in
|
case "$_cur" in
|
||||||
"$_new"*)
|
"$_new"*)
|
||||||
|
# the kit is current, but its core may not have got through last time
|
||||||
|
# (release published after the kit, download failed): retry it, only
|
||||||
|
# when it is there, so a missing release does not restart nikki nightly
|
||||||
|
if core_ok; then
|
||||||
auto_log "up to date ($_new)"
|
auto_log "up to date ($_new)"
|
||||||
|
elif core_available; then
|
||||||
|
auto_log "up to date ($_new), installing core $MIHOMO_VERSION"
|
||||||
|
cmd_fix
|
||||||
|
core_ok || auto_log "core $MIHOMO_VERSION still not installed"
|
||||||
|
else
|
||||||
|
auto_log "up to date ($_new), core $MIHOMO_VERSION not downloadable yet"
|
||||||
|
fi
|
||||||
return 0
|
return 0
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|||||||
@ -1,14 +1,15 @@
|
|||||||
diff --git a/adapter/outbound/openvpn.go b/adapter/outbound/openvpn.go
|
diff --git a/adapter/outbound/openvpn.go b/adapter/outbound/openvpn.go
|
||||||
index 3c7b1e6..3c1b947 100644
|
index 3c7b1e6..9225b4f 100644
|
||||||
--- a/adapter/outbound/openvpn.go
|
--- a/adapter/outbound/openvpn.go
|
||||||
+++ b/adapter/outbound/openvpn.go
|
+++ b/adapter/outbound/openvpn.go
|
||||||
@@ -2,12 +2,14 @@ package outbound
|
@@ -2,12 +2,15 @@ package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
+ "encoding/json"
|
+ "encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
+ "math/rand"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
@ -17,18 +18,17 @@ index 3c7b1e6..3c1b947 100644
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/contextutils"
|
"github.com/metacubex/mihomo/common/contextutils"
|
||||||
@@ -35,6 +37,21 @@ type OpenVPN struct {
|
@@ -35,6 +38,20 @@ type OpenVPN struct {
|
||||||
runCancel context.CancelFunc
|
runCancel context.CancelFunc
|
||||||
runLock *semaphore.Weighted
|
runLock *semaphore.Weighted
|
||||||
running bool
|
running bool
|
||||||
+
|
+
|
||||||
+ // auto-connect state, guarded by runLock: the session auth-token reused
|
+ // auto-connect state, guarded by runLock: the session auth-token reused
|
||||||
+ // on reconnect, credentials the server rejected, and the channel closed
|
+ // on reconnect, credentials the server rejected, and the current tunnel.
|
||||||
+ // when the current tunnel goes down.
|
|
||||||
+ tokenUser string
|
+ tokenUser string
|
||||||
+ tokenPass string
|
+ tokenPass string
|
||||||
+ authFailed bool
|
+ authFailed bool
|
||||||
+ linkDown chan struct{}
|
+ link *openVPNLink
|
||||||
+
|
+
|
||||||
+ // tunnel state for the API (MarshalJSON), readable without runLock:
|
+ // tunnel state for the API (MarshalJSON), readable without runLock:
|
||||||
+ // when the current tunnel came up (unix seconds, 0 = down), whether the
|
+ // when the current tunnel came up (unix seconds, 0 = down), whether the
|
||||||
@ -39,7 +39,7 @@ index 3c7b1e6..3c1b947 100644
|
|||||||
}
|
}
|
||||||
|
|
||||||
type OpenVPNOption struct {
|
type OpenVPNOption struct {
|
||||||
@@ -59,12 +76,18 @@ type OpenVPNOption struct {
|
@@ -59,12 +76,28 @@ type OpenVPNOption struct {
|
||||||
Username string `proxy:"username,omitempty"`
|
Username string `proxy:"username,omitempty"`
|
||||||
Password string `proxy:"password,omitempty"`
|
Password string `proxy:"password,omitempty"`
|
||||||
PeerInfo map[string]string `proxy:"peer-info,omitempty"`
|
PeerInfo map[string]string `proxy:"peer-info,omitempty"`
|
||||||
@ -55,12 +55,22 @@ index 3c7b1e6..3c1b947 100644
|
|||||||
+ // proxy is created, reconnect 2 s after the link drops with the session
|
+ // proxy is created, reconnect 2 s after the link drops with the session
|
||||||
+ // auth-token, stop after AUTH_FAILED until new credentials (a new proxy).
|
+ // auth-token, stop after AUTH_FAILED until new credentials (a new proxy).
|
||||||
+ AutoConnect bool `proxy:"auto-connect,omitempty"`
|
+ AutoConnect bool `proxy:"auto-connect,omitempty"`
|
||||||
|
+ // Pauses of an auto-connect proxy before the next attempt, in seconds:
|
||||||
|
+ // ReconnectPause (default 120) after a dropped tunnel, a failed connect
|
||||||
|
+ // or rejected credentials, doubled while attempts keep failing or tunnels
|
||||||
|
+ // drop within 5 minutes, up to 10 minutes; KickPause (default
|
||||||
|
+ // ReconnectPause) after the server ended the session (RESTART/HALT/EXIT),
|
||||||
|
+ // doubled for each kick in a row, up to 30 minutes. ReconnectJitter
|
||||||
|
+ // (default 30) spreads every pause by up to that many seconds either way.
|
||||||
|
+ ReconnectPause int `proxy:"reconnect-pause,omitempty"`
|
||||||
|
+ KickPause int `proxy:"kick-pause,omitempty"`
|
||||||
|
+ ReconnectJitter *int `proxy:"reconnect-jitter,omitempty"`
|
||||||
+ MTU int `proxy:"mtu,omitempty"`
|
+ MTU int `proxy:"mtu,omitempty"`
|
||||||
+ UDP bool `proxy:"udp,omitempty"`
|
+ UDP bool `proxy:"udp,omitempty"`
|
||||||
|
|
||||||
IPStack IPStackOption `proxy:"ip-stack,omitempty"`
|
IPStack IPStackOption `proxy:"ip-stack,omitempty"`
|
||||||
|
|
||||||
@@ -117,6 +140,8 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
|
@@ -117,6 +150,8 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
|
||||||
Username: option.Username,
|
Username: option.Username,
|
||||||
Password: option.Password,
|
Password: option.Password,
|
||||||
PeerInfo: option.PeerInfo,
|
PeerInfo: option.PeerInfo,
|
||||||
@ -69,7 +79,7 @@ index 3c7b1e6..3c1b947 100644
|
|||||||
PingInterval: time.Duration(option.Ping) * time.Second,
|
PingInterval: time.Duration(option.Ping) * time.Second,
|
||||||
PingRestart: time.Duration(option.PingRestart) * time.Second,
|
PingRestart: time.Duration(option.PingRestart) * time.Second,
|
||||||
TransitionWindow: transitionWindow,
|
TransitionWindow: transitionWindow,
|
||||||
@@ -152,9 +177,115 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
|
@@ -152,9 +187,245 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
|
||||||
}
|
}
|
||||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
outbound.runCtx, outbound.runCancel = context.WithCancel(context.Background())
|
outbound.runCtx, outbound.runCancel = context.WithCancel(context.Background())
|
||||||
@ -127,65 +137,195 @@ index 3c7b1e6..3c1b947 100644
|
|||||||
+ wg.Wait()
|
+ wg.Wait()
|
||||||
+}
|
+}
|
||||||
+
|
+
|
||||||
+// openVPNRestartDelay is OpenVPN Connect's pause before a reconnect; it
|
+// An auto-connect proxy never reconnects right away: a quick reconnect after
|
||||||
+// doubles after each failed connect up to openVPNRestartMax and starts over
|
+// the server dropped or kicked the session gets the account blocked. Every
|
||||||
+// once a tunnel comes up.
|
+// end of an attempt (a tunnel down, a failed connect, rejected credentials)
|
||||||
|
+// starts a pause, with jitter so the attempts do not keep a clock.
|
||||||
+const (
|
+const (
|
||||||
+ openVPNRestartDelay = 2 * time.Second
|
+ // after a drop, a failed connect or rejected credentials; doubled while
|
||||||
+ openVPNRestartMax = time.Minute
|
+ // attempts fail or tunnels drop within openVPNStableAfter
|
||||||
|
+ openVPNPause = 2 * time.Minute
|
||||||
|
+ openVPNPauseMax = 10 * time.Minute
|
||||||
|
+ openVPNStableAfter = 5 * time.Minute
|
||||||
|
+ // after the server ended the session (RESTART/HALT/EXIT: a client-kill,
|
||||||
|
+ // for one); doubled for each kick in a row, a session that lasted
|
||||||
|
+ // openVPNKickForget before its kick starts the count over
|
||||||
|
+ openVPNKickMax = 30 * time.Minute
|
||||||
|
+ openVPNKickForget = 30 * time.Minute
|
||||||
|
+ openVPNJitter = 30 * time.Second
|
||||||
+)
|
+)
|
||||||
+
|
+
|
||||||
+var errOpenVPNAuthRejected = errors.New("openvpn credentials were rejected, waiting for new ones")
|
+// why a pause started (openvpn.retry_why in the API)
|
||||||
|
+const (
|
||||||
|
+ openVPNWhyDrop = "drop"
|
||||||
|
+ openVPNWhyKick = "kick"
|
||||||
|
+ openVPNWhyFailed = "failed"
|
||||||
|
+ openVPNWhyRejected = "rejected"
|
||||||
|
+)
|
||||||
+
|
+
|
||||||
|
+var (
|
||||||
|
+ errOpenVPNAuthRejected = errors.New("openvpn credentials were rejected, waiting for new ones")
|
||||||
|
+ errOpenVPNPaused = errors.New("openvpn reconnect pause")
|
||||||
|
+)
|
||||||
|
+
|
||||||
|
+// openVPNLink is one tunnel of an auto-connect proxy: down is closed when it
|
||||||
|
+// goes down.
|
||||||
|
+type openVPNLink struct {
|
||||||
|
+ down chan struct{}
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// openVPNHolds are the pauses by provider and proxy name, guarded by
|
||||||
|
+// openVPNMu. They outlive the proxy: a provider or config reload replaces it,
|
||||||
|
+// and the new one must not connect before the pause is over either.
|
||||||
|
+type openVPNHold struct {
|
||||||
|
+ until time.Time
|
||||||
|
+ why string
|
||||||
|
+ strikes int // failed attempts and short tunnels in a row
|
||||||
|
+ kicks int // kicks in a row
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+var openVPNHolds = map[string]*openVPNHold{}
|
||||||
|
+
|
||||||
|
+func (o *OpenVPN) holdKey() string {
|
||||||
|
+ return o.option.ProviderName + "\x00" + o.name
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// hold is the current pause: its end (zero when there is none) and why.
|
||||||
|
+func (o *OpenVPN) hold() (time.Time, string) {
|
||||||
|
+ openVPNMu.Lock()
|
||||||
|
+ defer openVPNMu.Unlock()
|
||||||
|
+ if h := openVPNHolds[o.holdKey()]; h != nil {
|
||||||
|
+ return h.until, h.why
|
||||||
|
+ }
|
||||||
|
+ return time.Time{}, ""
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func (o *OpenVPN) holdUntil() time.Time {
|
||||||
|
+ until, _ := o.hold()
|
||||||
|
+ return until
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// doublePause doubles pause times, up to limit (or pause, when longer).
|
||||||
|
+func doublePause(pause time.Duration, times int, limit time.Duration) time.Duration {
|
||||||
|
+ if limit < pause {
|
||||||
|
+ return pause
|
||||||
|
+ }
|
||||||
|
+ for i := 0; i < times && pause < limit; i++ {
|
||||||
|
+ pause *= 2
|
||||||
|
+ }
|
||||||
|
+ if pause > limit {
|
||||||
|
+ pause = limit
|
||||||
|
+ }
|
||||||
|
+ return pause
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// pauseAfter starts the pause after an attempt that ended for why, with the
|
||||||
|
+// tunnel up for lived (0 when it never came up), and returns it.
|
||||||
|
+func (o *OpenVPN) pauseAfter(why string, lived time.Duration) time.Duration {
|
||||||
|
+ base := openVPNPause
|
||||||
|
+ if o.option.ReconnectPause > 0 {
|
||||||
|
+ base = time.Duration(o.option.ReconnectPause) * time.Second
|
||||||
|
+ }
|
||||||
|
+ kickBase := base
|
||||||
|
+ if o.option.KickPause > 0 {
|
||||||
|
+ kickBase = time.Duration(o.option.KickPause) * time.Second
|
||||||
|
+ }
|
||||||
|
+ jitter := openVPNJitter
|
||||||
|
+ if o.option.ReconnectJitter != nil {
|
||||||
|
+ jitter = time.Duration(*o.option.ReconnectJitter) * time.Second
|
||||||
|
+ }
|
||||||
|
+ openVPNMu.Lock()
|
||||||
|
+ defer openVPNMu.Unlock()
|
||||||
|
+ h := openVPNHolds[o.holdKey()]
|
||||||
|
+ if h == nil {
|
||||||
|
+ h = &openVPNHold{}
|
||||||
|
+ openVPNHolds[o.holdKey()] = h
|
||||||
|
+ }
|
||||||
|
+ if lived >= openVPNStableAfter {
|
||||||
|
+ h.strikes = 0
|
||||||
|
+ }
|
||||||
|
+ if lived >= openVPNKickForget {
|
||||||
|
+ h.kicks = 0
|
||||||
|
+ }
|
||||||
|
+ var pause time.Duration
|
||||||
|
+ if why == openVPNWhyKick {
|
||||||
|
+ pause = doublePause(kickBase, h.kicks, openVPNKickMax)
|
||||||
|
+ h.kicks++
|
||||||
|
+ } else {
|
||||||
|
+ pause = doublePause(base, h.strikes, openVPNPauseMax)
|
||||||
|
+ h.strikes++
|
||||||
|
+ }
|
||||||
|
+ if jitter > 0 {
|
||||||
|
+ pause += time.Duration(rand.Int63n(int64(2*jitter)+1)) - jitter
|
||||||
|
+ }
|
||||||
|
+ if pause < time.Second {
|
||||||
|
+ pause = time.Second
|
||||||
|
+ }
|
||||||
|
+ h.until, h.why = time.Now().Add(pause), why
|
||||||
|
+ return pause
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// sleep waits d, false when the proxy was closed meanwhile.
|
||||||
|
+func (o *OpenVPN) sleep(d time.Duration) bool {
|
||||||
|
+ if d <= 0 {
|
||||||
|
+ return o.runCtx.Err() == nil
|
||||||
|
+ }
|
||||||
|
+ t := time.NewTimer(d)
|
||||||
|
+ defer t.Stop()
|
||||||
|
+ select {
|
||||||
|
+ case <-t.C:
|
||||||
|
+ return true
|
||||||
|
+ case <-o.runCtx.Done():
|
||||||
|
+ return false
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// autoConnect keeps the tunnel up. The pauses are set where an attempt ends
|
||||||
|
+// (run, the packet loops), so no attempt, on demand either, starts in one.
|
||||||
+func (o *OpenVPN) autoConnect() {
|
+func (o *OpenVPN) autoConnect() {
|
||||||
+ delay := openVPNRestartDelay
|
+ for {
|
||||||
+ for o.runCtx.Err() == nil {
|
+ if until, why := o.hold(); time.Now().Before(until) {
|
||||||
|
+ log.Infoln("[OpenVPN](%s) reconnect pause (%s), connecting at %s", o.name, why, until.Format("15:04:05"))
|
||||||
|
+ if !o.sleep(time.Until(until)) {
|
||||||
|
+ return
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
+ _, _, err := o.run(o.runCtx)
|
+ _, _, err := o.run(o.runCtx)
|
||||||
+ if o.runCtx.Err() != nil {
|
+ if o.runCtx.Err() != nil {
|
||||||
+ return
|
+ return
|
||||||
+ }
|
+ }
|
||||||
|
+ if errors.Is(err, errOpenVPNPaused) {
|
||||||
|
+ continue
|
||||||
|
+ }
|
||||||
+ if err != nil {
|
+ if err != nil {
|
||||||
+ o.lastErr.Store(err.Error())
|
+ o.lastErr.Store(err.Error())
|
||||||
+ }
|
|
||||||
+ if errors.Is(err, errOpenVPNAuthRejected) {
|
+ if errors.Is(err, errOpenVPNAuthRejected) {
|
||||||
+ log.Warnln("[OpenVPN](%s) %v", o.name, err)
|
+ log.Warnln("[OpenVPN](%s) %v", o.name, err)
|
||||||
+ return
|
+ return
|
||||||
+ }
|
+ }
|
||||||
+ if err != nil {
|
+ log.Warnln("[OpenVPN](%s) connect failed: %v", o.name, err)
|
||||||
+ log.Warnln("[OpenVPN](%s) connect failed, retrying in %s: %v", o.name, delay, err)
|
+ continue
|
||||||
+ } else {
|
+ }
|
||||||
+ delay = openVPNRestartDelay
|
+ var link *openVPNLink
|
||||||
+ var down chan struct{}
|
|
||||||
+ if o.runLock.Acquire(o.runCtx, 1) == nil {
|
+ if o.runLock.Acquire(o.runCtx, 1) == nil {
|
||||||
+ down = o.linkDown
|
+ link = o.link
|
||||||
+ o.runLock.Release(1)
|
+ o.runLock.Release(1)
|
||||||
+ }
|
+ }
|
||||||
+ if down != nil {
|
+ if link == nil {
|
||||||
+ select {
|
+ continue
|
||||||
+ case <-down:
|
|
||||||
+ case <-o.runCtx.Done():
|
|
||||||
+ return
|
|
||||||
+ }
|
|
||||||
+ log.Infoln("[OpenVPN](%s) tunnel down, reconnecting in %s", o.name, openVPNRestartDelay)
|
|
||||||
+ }
|
|
||||||
+ }
|
+ }
|
||||||
+ select {
|
+ select {
|
||||||
+ case <-time.After(delay):
|
+ case <-link.down:
|
||||||
+ case <-o.runCtx.Done():
|
+ case <-o.runCtx.Done():
|
||||||
+ return
|
+ return
|
||||||
+ }
|
+ }
|
||||||
+ if err != nil {
|
|
||||||
+ if delay *= 2; delay > openVPNRestartMax {
|
|
||||||
+ delay = openVPNRestartMax
|
|
||||||
+ }
|
|
||||||
+ }
|
|
||||||
+ }
|
+ }
|
||||||
+}
|
+}
|
||||||
+
|
+
|
||||||
func (o *OpenVPN) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (o *OpenVPN) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
tunDevice, r, err := o.run(ctx)
|
tunDevice, r, err := o.run(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -223,6 +354,28 @@ func (o *OpenVPN) resolveUDP(ctx context.Context, metadata *C.Metadata, r resolv
|
@@ -223,6 +494,34 @@ func (o *OpenVPN) resolveUDP(ctx context.Context, metadata *C.Metadata, r resolv
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -203,6 +343,12 @@ index 3c7b1e6..3c1b947 100644
|
|||||||
+ "auto_connect": o.option.AutoConnect,
|
+ "auto_connect": o.option.AutoConnect,
|
||||||
+ "connected_since": o.upSince.Load(),
|
+ "connected_since": o.upSince.Load(),
|
||||||
+ "auth_failed": o.rejected.Load(),
|
+ "auth_failed": o.rejected.Load(),
|
||||||
|
+ "retry_at": int64(0),
|
||||||
|
+ }
|
||||||
|
+ // the reconnect pause: no attempt (and no new OTP) before then
|
||||||
|
+ if until, why := o.hold(); time.Now().Before(until) {
|
||||||
|
+ state["retry_at"] = until.Unix()
|
||||||
|
+ state["retry_why"] = why
|
||||||
+ }
|
+ }
|
||||||
+ if e, _ := o.lastErr.Load().(string); e != "" {
|
+ if e, _ := o.lastErr.Load().(string); e != "" {
|
||||||
+ state["last_error"] = e
|
+ state["last_error"] = e
|
||||||
@ -214,7 +360,7 @@ index 3c7b1e6..3c1b947 100644
|
|||||||
func (o *OpenVPN) ProxyInfo() C.ProxyInfo {
|
func (o *OpenVPN) ProxyInfo() C.ProxyInfo {
|
||||||
info := o.Base.ProxyInfo()
|
info := o.Base.ProxyInfo()
|
||||||
info.DialerProxy = o.option.DialerProxy
|
info.DialerProxy = o.option.DialerProxy
|
||||||
@@ -234,6 +387,22 @@ func (o *OpenVPN) IsL3Protocol(metadata *C.Metadata) bool {
|
@@ -234,6 +533,22 @@ func (o *OpenVPN) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *OpenVPN) Close() error {
|
func (o *OpenVPN) Close() error {
|
||||||
@ -237,7 +383,7 @@ index 3c7b1e6..3c1b947 100644
|
|||||||
if o.runCancel != nil {
|
if o.runCancel != nil {
|
||||||
o.runCancel()
|
o.runCancel()
|
||||||
}
|
}
|
||||||
@@ -243,6 +412,7 @@ func (o *OpenVPN) Close() error {
|
@@ -243,6 +558,7 @@ func (o *OpenVPN) Close() error {
|
||||||
o.client = nil
|
o.client = nil
|
||||||
o.tunDevice = nil
|
o.tunDevice = nil
|
||||||
o.running = false
|
o.running = false
|
||||||
@ -245,17 +391,56 @@ index 3c7b1e6..3c1b947 100644
|
|||||||
o.runLock.Release(1)
|
o.runLock.Release(1)
|
||||||
|
|
||||||
if client != nil {
|
if client != nil {
|
||||||
@@ -278,6 +448,9 @@ func (o *OpenVPN) run(ctx context.Context) (ipStack, resolver.Resolver, error) {
|
@@ -278,6 +594,15 @@ func (o *OpenVPN) run(ctx context.Context) (ipStack, resolver.Resolver, error) {
|
||||||
}
|
}
|
||||||
return o.tunDevice, o.resolver, nil
|
return o.tunDevice, o.resolver, nil
|
||||||
}
|
}
|
||||||
+ if o.authFailed {
|
+ if o.authFailed {
|
||||||
+ return nil, nil, errOpenVPNAuthRejected
|
+ return nil, nil, errOpenVPNAuthRejected
|
||||||
|
+ }
|
||||||
|
+ if o.option.AutoConnect {
|
||||||
|
+ // no tunnel on demand either while a reconnect pause lasts
|
||||||
|
+ if until, why := o.hold(); time.Now().Before(until) {
|
||||||
|
+ return nil, nil, fmt.Errorf("%w (%s) until %s", errOpenVPNPaused, why, until.Format("15:04:05"))
|
||||||
|
+ }
|
||||||
+ }
|
+ }
|
||||||
if o.runCtx.Err() != nil {
|
if o.runCtx.Err() != nil {
|
||||||
return nil, nil, o.runCtx.Err()
|
return nil, nil, o.runCtx.Err()
|
||||||
}
|
}
|
||||||
@@ -318,7 +491,17 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R
|
@@ -298,7 +623,7 @@ func (o *OpenVPN) run(ctx context.Context) (ipStack, resolver.Resolver, error) {
|
||||||
|
handshakeCtx, handshakeCancel := context.WithTimeout(o.runCtx, handshakeTimeout)
|
||||||
|
defer handshakeCancel()
|
||||||
|
|
||||||
|
- tunDevice, r, err := o.startLocked(handshakeCtx)
|
||||||
|
+ tunDevice, r, err := o.attemptLocked(handshakeCtx)
|
||||||
|
resultCh <- runResult{tunDevice: tunDevice, resolver: r, err: err}
|
||||||
|
}()
|
||||||
|
|
||||||
|
@@ -310,7 +635,22 @@ func (o *OpenVPN) run(ctx context.Context) (ipStack, resolver.Resolver, error) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
- return o.startLocked(runCtx)
|
||||||
|
+ return o.attemptLocked(runCtx)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// attemptLocked is startLocked that starts the reconnect pause of an
|
||||||
|
+// auto-connect proxy when the attempt fails.
|
||||||
|
+func (o *OpenVPN) attemptLocked(handshakeCtx context.Context) (ipStack, resolver.Resolver, error) {
|
||||||
|
+ tunDevice, r, err := o.startLocked(handshakeCtx)
|
||||||
|
+ if err != nil && o.option.AutoConnect && o.runCtx.Err() == nil {
|
||||||
|
+ why := openVPNWhyFailed
|
||||||
|
+ if errors.Is(err, errOpenVPNAuthRejected) {
|
||||||
|
+ why = openVPNWhyRejected
|
||||||
|
+ }
|
||||||
|
+ pause := o.pauseAfter(why, 0)
|
||||||
|
+ log.Warnln("[OpenVPN](%s) connect failed, no attempt for %s: %v", o.name, pause.Round(time.Second), err)
|
||||||
|
+ }
|
||||||
|
+ return tunDevice, r, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.Resolver, error) {
|
||||||
|
@@ -318,7 +658,17 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, fmt.Errorf("connect OpenVPN server: %w", err)
|
return nil, nil, fmt.Errorf("connect OpenVPN server: %w", err)
|
||||||
}
|
}
|
||||||
@ -274,7 +459,7 @@ index 3c7b1e6..3c1b947 100644
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
_ = packetIO.Close()
|
_ = packetIO.Close()
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
@@ -326,6 +509,15 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R
|
@@ -326,6 +676,15 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R
|
||||||
push, err := client.Handshake(handshakeCtx)
|
push, err := client.Handshake(handshakeCtx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = client.Close()
|
_ = client.Close()
|
||||||
@ -290,25 +475,30 @@ index 3c7b1e6..3c1b947 100644
|
|||||||
return nil, nil, fmt.Errorf("make OpenVPN handshake: %w", 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)
|
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 +539,9 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R
|
@@ -347,6 +706,9 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R
|
||||||
o.client = client
|
o.client = client
|
||||||
o.tunDevice = tunDevice
|
o.tunDevice = tunDevice
|
||||||
o.running = true
|
o.running = true
|
||||||
+ o.linkDown = make(chan struct{})
|
+ o.link = &openVPNLink{down: make(chan struct{})}
|
||||||
+ o.upSince.Store(time.Now().Unix())
|
+ o.upSince.Store(time.Now().Unix())
|
||||||
+ o.lastErr.Store("")
|
+ o.lastErr.Store("")
|
||||||
if o.option.RemoteDnsResolve && len(o.dns) > 0 && o.resolver == nil {
|
if o.option.RemoteDnsResolve && len(o.dns) > 0 && o.resolver == nil {
|
||||||
nss := append([]dns.NameServer(nil), o.dns...)
|
nss := append([]dns.NameServer(nil), o.dns...)
|
||||||
for i := range nss {
|
for i := range nss {
|
||||||
@@ -393,6 +588,7 @@ func (o *OpenVPN) startPacketLoops() {
|
@@ -393,6 +755,7 @@ func (o *OpenVPN) startPacketLoops() {
|
||||||
runCtx, runCancel := context.WithCancel(o.runCtx)
|
runCtx, runCancel := context.WithCancel(o.runCtx)
|
||||||
client := o.client
|
client := o.client
|
||||||
tunDevice := o.tunDevice
|
tunDevice := o.tunDevice
|
||||||
+ linkDown := o.linkDown
|
+ link := o.link
|
||||||
var stopOnce sync.Once
|
var stopOnce sync.Once
|
||||||
stop := func() {
|
stop := func() {
|
||||||
stopOnce.Do(func() {
|
stopOnce.Do(func() {
|
||||||
@@ -404,8 +600,13 @@ func (o *OpenVPN) startPacketLoops() {
|
@@ -400,12 +763,41 @@ func (o *OpenVPN) startPacketLoops() {
|
||||||
|
_ = client.Close()
|
||||||
|
_ = tunDevice.Close()
|
||||||
|
_ = o.runLock.Acquire(context.Background(), 1)
|
||||||
|
+ since := o.upSince.Load()
|
||||||
|
if o.client == client {
|
||||||
o.client = nil
|
o.client = nil
|
||||||
o.tunDevice = nil
|
o.tunDevice = nil
|
||||||
o.running = false
|
o.running = false
|
||||||
@ -316,25 +506,53 @@ index 3c7b1e6..3c1b947 100644
|
|||||||
+ }
|
+ }
|
||||||
+ if user, pass, ok := client.AuthToken(); ok {
|
+ if user, pass, ok := client.AuthToken(); ok {
|
||||||
+ o.tokenUser, o.tokenPass = user, pass
|
+ o.tokenUser, o.tokenPass = user, pass
|
||||||
|
+ }
|
||||||
|
+ // a drop, not a local close: pause before the next attempt,
|
||||||
|
+ // set before runLock is released so no dial slips in
|
||||||
|
+ if o.option.AutoConnect && o.runCtx.Err() == nil {
|
||||||
|
+ var lived time.Duration
|
||||||
|
+ if since > 0 {
|
||||||
|
+ lived = time.Since(time.Unix(since, 0)).Round(time.Second)
|
||||||
|
+ }
|
||||||
|
+ why := openVPNWhyDrop
|
||||||
|
+ err := client.LastRekeyError()
|
||||||
|
+ // RESTART/HALT/EXIT from the server (kept apart: its own pause)
|
||||||
|
+ if ovpn.IsServerTerminated(err) {
|
||||||
|
+ why = openVPNWhyKick
|
||||||
|
+ }
|
||||||
|
+ if err != nil {
|
||||||
|
+ o.lastErr.Store(err.Error())
|
||||||
|
+ } else {
|
||||||
|
+ o.lastErr.Store(fmt.Sprintf("tunnel down after %s", lived))
|
||||||
|
+ }
|
||||||
|
+ pause := o.pauseAfter(why, lived)
|
||||||
|
+ log.Warnln("[OpenVPN](%s) tunnel down (%s) after %s, reconnecting in %s", o.name, why, lived, pause.Round(time.Second))
|
||||||
}
|
}
|
||||||
o.runLock.Release(1)
|
o.runLock.Release(1)
|
||||||
+ close(linkDown)
|
+ if link != nil {
|
||||||
|
+ close(link.down)
|
||||||
|
+ }
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
go func() {
|
go func() {
|
||||||
diff --git a/adapter/outbound/openvpn_state_test.go b/adapter/outbound/openvpn_state_test.go
|
diff --git a/adapter/outbound/openvpn_state_test.go b/adapter/outbound/openvpn_state_test.go
|
||||||
new file mode 100644
|
new file mode 100644
|
||||||
index 0000000..078fb12
|
index 0000000..860f782
|
||||||
--- /dev/null
|
--- /dev/null
|
||||||
+++ b/adapter/outbound/openvpn_state_test.go
|
+++ b/adapter/outbound/openvpn_state_test.go
|
||||||
@@ -0,0 +1,41 @@
|
@@ -0,0 +1,141 @@
|
||||||
+package outbound
|
+package outbound
|
||||||
+
|
+
|
||||||
+import (
|
+import (
|
||||||
|
+ "context"
|
||||||
+ "encoding/json"
|
+ "encoding/json"
|
||||||
|
+ "errors"
|
||||||
+ "testing"
|
+ "testing"
|
||||||
|
+ "time"
|
||||||
+
|
+
|
||||||
+ C "github.com/metacubex/mihomo/constant"
|
+ C "github.com/metacubex/mihomo/constant"
|
||||||
|
+
|
||||||
|
+ "golang.org/x/sync/semaphore"
|
||||||
+)
|
+)
|
||||||
+
|
+
|
||||||
+func TestOpenVPNStateJSON(t *testing.T) {
|
+func TestOpenVPNStateJSON(t *testing.T) {
|
||||||
@ -369,6 +587,101 @@ index 0000000..078fb12
|
|||||||
+ t.Fatalf("wrapper hides the state: %s", raw2)
|
+ t.Fatalf("wrapper hides the state: %s", raw2)
|
||||||
+ }
|
+ }
|
||||||
+}
|
+}
|
||||||
|
+
|
||||||
|
+func newPauseTestOpenVPN(name string, pause, kick int, jitter *int) *OpenVPN {
|
||||||
|
+ o := &OpenVPN{Base: &Base{name: name}, option: &OpenVPNOption{
|
||||||
|
+ BasicOption: BasicOption{ProviderName: "p"}, AutoConnect: true,
|
||||||
|
+ ReconnectPause: pause, KickPause: kick, ReconnectJitter: jitter,
|
||||||
|
+ }}
|
||||||
|
+ return o
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func dropPauseTestOpenVPN(o *OpenVPN) {
|
||||||
|
+ openVPNMu.Lock()
|
||||||
|
+ delete(openVPNHolds, o.holdKey())
|
||||||
|
+ openVPNMu.Unlock()
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestOpenVPNReconnectPause(t *testing.T) {
|
||||||
|
+ noJitter := 0
|
||||||
|
+ o := newPauseTestOpenVPN("pause-test", 0, 0, &noJitter)
|
||||||
|
+ defer dropPauseTestOpenVPN(o)
|
||||||
|
+ steps := []struct {
|
||||||
|
+ why string
|
||||||
|
+ lived time.Duration
|
||||||
|
+ want time.Duration
|
||||||
|
+ }{
|
||||||
|
+ // a long session, then a silent drop: the base pause
|
||||||
|
+ {openVPNWhyDrop, time.Hour, 2 * time.Minute},
|
||||||
|
+ // connects fail and tunnels drop soon after coming up: doubled
|
||||||
|
+ {openVPNWhyFailed, 0, 4 * time.Minute},
|
||||||
|
+ {openVPNWhyDrop, time.Minute, 8 * time.Minute},
|
||||||
|
+ {openVPNWhyFailed, 0, 10 * time.Minute},
|
||||||
|
+ // kicks count apart from the rest
|
||||||
|
+ {openVPNWhyKick, time.Minute, 2 * time.Minute},
|
||||||
|
+ {openVPNWhyKick, time.Minute, 4 * time.Minute},
|
||||||
|
+ {openVPNWhyKick, time.Minute, 8 * time.Minute},
|
||||||
|
+ {openVPNWhyKick, time.Minute, 16 * time.Minute},
|
||||||
|
+ {openVPNWhyKick, time.Minute, 30 * time.Minute},
|
||||||
|
+ // a stable tunnel starts the strikes over, a long one the kicks too
|
||||||
|
+ {openVPNWhyDrop, openVPNStableAfter, 2 * time.Minute},
|
||||||
|
+ {openVPNWhyKick, openVPNKickForget, 2 * time.Minute},
|
||||||
|
+ {openVPNWhyRejected, 0, 2 * time.Minute},
|
||||||
|
+ {openVPNWhyFailed, 0, 4 * time.Minute},
|
||||||
|
+ }
|
||||||
|
+ for i, st := range steps {
|
||||||
|
+ if got := o.pauseAfter(st.why, st.lived); got != st.want {
|
||||||
|
+ t.Fatalf("step %d (%s after %s): pause %s, want %s", i+1, st.why, st.lived, got, st.want)
|
||||||
|
+ }
|
||||||
|
+ if _, why := o.hold(); why != st.why {
|
||||||
|
+ t.Fatalf("step %d: hold why %q", i+1, why)
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ // the pause outlives the proxy: a replacement from the provider sees it
|
||||||
|
+ o2 := newPauseTestOpenVPN("pause-test", 0, 0, nil)
|
||||||
|
+ if until := o2.holdUntil(); time.Until(until) < time.Minute {
|
||||||
|
+ t.Fatalf("replacement proxy does not see the pause: %s", until)
|
||||||
|
+ }
|
||||||
|
+ o2.runCtx, o2.runCancel = context.WithCancel(context.Background())
|
||||||
|
+ defer o2.runCancel()
|
||||||
|
+ o2.runLock = semaphore.NewWeighted(1)
|
||||||
|
+ if _, _, err := o2.run(context.Background()); !errors.Is(err, errOpenVPNPaused) {
|
||||||
|
+ t.Fatalf("run during the pause: %v", err)
|
||||||
|
+ }
|
||||||
|
+ raw, _ := o2.MarshalJSON()
|
||||||
|
+ var got struct {
|
||||||
|
+ OpenVPN struct {
|
||||||
|
+ RetryAt int64 `json:"retry_at"`
|
||||||
|
+ RetryWhy string `json:"retry_why"`
|
||||||
|
+ } `json:"openvpn"`
|
||||||
|
+ }
|
||||||
|
+ _ = json.Unmarshal(raw, &got)
|
||||||
|
+ if got.OpenVPN.RetryAt <= time.Now().Unix() || got.OpenVPN.RetryWhy != openVPNWhyFailed {
|
||||||
|
+ t.Fatalf("pause not reported: %s", raw)
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestOpenVPNPauseJitter(t *testing.T) {
|
||||||
|
+ o := newPauseTestOpenVPN("jitter-test", 60, 300, nil)
|
||||||
|
+ defer dropPauseTestOpenVPN(o)
|
||||||
|
+ seen := map[time.Duration]bool{}
|
||||||
|
+ for i := 0; i < 200; i++ {
|
||||||
|
+ lo, hi := 30*time.Second, 90*time.Second
|
||||||
|
+ why := openVPNWhyDrop
|
||||||
|
+ if i%2 == 1 {
|
||||||
|
+ why, lo, hi = openVPNWhyKick, 270*time.Second, 330*time.Second
|
||||||
|
+ }
|
||||||
|
+ got := o.pauseAfter(why, openVPNKickForget)
|
||||||
|
+ if got < lo || got > hi {
|
||||||
|
+ t.Fatalf("%s pause %s outside %s..%s", why, got, lo, hi)
|
||||||
|
+ }
|
||||||
|
+ seen[got] = true
|
||||||
|
+ }
|
||||||
|
+ if len(seen) < 20 {
|
||||||
|
+ t.Fatalf("no jitter: %d distinct pauses", len(seen))
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
diff --git a/adapter/provider/provider.go b/adapter/provider/provider.go
|
diff --git a/adapter/provider/provider.go b/adapter/provider/provider.go
|
||||||
index fa7d56b..c472539 100644
|
index fa7d56b..c472539 100644
|
||||||
--- a/adapter/provider/provider.go
|
--- a/adapter/provider/provider.go
|
||||||
@ -417,7 +730,7 @@ index 796face..a7df5cd 100644
|
|||||||
tproxy.CleanupTProxyIPTables()
|
tproxy.CleanupTProxyIPTables()
|
||||||
resolver.StoreFakePoolState()
|
resolver.StoreFakePoolState()
|
||||||
diff --git a/transport/openvpn/client.go b/transport/openvpn/client.go
|
diff --git a/transport/openvpn/client.go b/transport/openvpn/client.go
|
||||||
index 053b0bf..c7e7848 100644
|
index 053b0bf..3fe942f 100644
|
||||||
--- a/transport/openvpn/client.go
|
--- a/transport/openvpn/client.go
|
||||||
+++ b/transport/openvpn/client.go
|
+++ b/transport/openvpn/client.go
|
||||||
@@ -286,12 +286,15 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) {
|
@@ -286,12 +286,15 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) {
|
||||||
@ -480,7 +793,7 @@ index 053b0bf..c7e7848 100644
|
|||||||
c.installDataChannel(newData)
|
c.installDataChannel(newData)
|
||||||
c.captureAuthToken(push)
|
c.captureAuthToken(push)
|
||||||
c.markSend()
|
c.markSend()
|
||||||
@@ -387,6 +387,130 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) {
|
@@ -387,6 +387,136 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) {
|
||||||
return push, nil
|
return push, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -607,11 +920,17 @@ index 053b0bf..c7e7848 100644
|
|||||||
+func IsAuthFailedTemp(err error) bool {
|
+func IsAuthFailedTemp(err error) bool {
|
||||||
+ return IsAuthFailed(err) && strings.Contains(err.Error(), "AUTH_FAILED,TEMP")
|
+ return IsAuthFailed(err) && strings.Contains(err.Error(), "AUTH_FAILED,TEMP")
|
||||||
+}
|
+}
|
||||||
|
+
|
||||||
|
+// IsServerTerminated reports whether err is the server ending the session
|
||||||
|
+// with a RESTART, HALT or EXIT control message (a client-kill, for one).
|
||||||
|
+func IsServerTerminated(err error) bool {
|
||||||
|
+ return errors.Is(err, errControlTerminated)
|
||||||
|
+}
|
||||||
+
|
+
|
||||||
// consumeRekeyPush updates the cached push state after an authenticated
|
// consumeRekeyPush updates the cached push state after an authenticated
|
||||||
// rekey: it inherits the previous peer-id and applies any fresh auth-token
|
// rekey: it inherits the previous peer-id and applies any fresh auth-token
|
||||||
// pushed by send_push_reply_auth_token. Must be called only when c.push is
|
// pushed by send_push_reply_auth_token. Must be called only when c.push is
|
||||||
@@ -1652,6 +1776,10 @@ func mergePushReply(prev, next *PushReply) *PushReply {
|
@@ -1652,6 +1782,10 @@ func mergePushReply(prev, next *PushReply) *PushReply {
|
||||||
if !next.BlockIPv6 {
|
if !next.BlockIPv6 {
|
||||||
next.BlockIPv6 = prev.BlockIPv6
|
next.BlockIPv6 = prev.BlockIPv6
|
||||||
}
|
}
|
||||||
@ -622,7 +941,7 @@ index 053b0bf..c7e7848 100644
|
|||||||
if next.AuthTokenPass == "" {
|
if next.AuthTokenPass == "" {
|
||||||
next.AuthTokenPass = prev.AuthTokenPass
|
next.AuthTokenPass = prev.AuthTokenPass
|
||||||
}
|
}
|
||||||
@@ -1768,6 +1896,12 @@ func (c *Client) tlsConfig() (*tls.Config, error) {
|
@@ -1768,6 +1902,12 @@ func (c *Client) tlsConfig() (*tls.Config, error) {
|
||||||
// servers rekey the control channel at regular intervals (default 1h).
|
// servers rekey the control channel at regular intervals (default 1h).
|
||||||
Renegotiation: tls.RenegotiateFreelyAsClient,
|
Renegotiation: tls.RenegotiateFreelyAsClient,
|
||||||
}
|
}
|
||||||
@ -1592,10 +1911,10 @@ index df84904..419695a 100644
|
|||||||
reply.AuthTokenPass = strings.TrimSpace(fields[1])
|
reply.AuthTokenPass = strings.TrimSpace(fields[1])
|
||||||
diff --git a/transport/openvpn/push_mimic_test.go b/transport/openvpn/push_mimic_test.go
|
diff --git a/transport/openvpn/push_mimic_test.go b/transport/openvpn/push_mimic_test.go
|
||||||
new file mode 100644
|
new file mode 100644
|
||||||
index 0000000..7149f3c
|
index 0000000..d1e356f
|
||||||
--- /dev/null
|
--- /dev/null
|
||||||
+++ b/transport/openvpn/push_mimic_test.go
|
+++ b/transport/openvpn/push_mimic_test.go
|
||||||
@@ -0,0 +1,32 @@
|
@@ -0,0 +1,44 @@
|
||||||
+package openvpn
|
+package openvpn
|
||||||
+
|
+
|
||||||
+import (
|
+import (
|
||||||
@ -1628,3 +1947,15 @@ index 0000000..7149f3c
|
|||||||
+ t.Fatalf("hard = %v", hard)
|
+ t.Fatalf("hard = %v", hard)
|
||||||
+ }
|
+ }
|
||||||
+}
|
+}
|
||||||
|
+
|
||||||
|
+func TestServerTerminated(t *testing.T) {
|
||||||
|
+ for _, msg := range []string{"RESTART\x00", "RESTART,kicked by admin\x00", "HALT,bye\x00", "EXIT\x00"} {
|
||||||
|
+ err := controlMessageError([]byte(msg))
|
||||||
|
+ if !IsServerTerminated(err) || IsAuthFailed(err) {
|
||||||
|
+ t.Fatalf("%q: %v", msg, err)
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+ if IsServerTerminated(controlMessageError([]byte("AUTH_FAILED\x00"))) {
|
||||||
|
+ t.Fatal("AUTH_FAILED taken for a kick")
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user