feat(proxy): tcp-режим для xray/sing-box поверх turn
This commit is contained in:
1 parent
e63279db18
commit
f7129099f7
60 files changed
+2953
-135
No files matched your search
@@ -10,7 +10,7 @@
|
||||
|
||||
## О проекте
|
||||
|
||||
**Free Turn Proxy** - прокси-туннель для инкапсуляции UDP-трафика поверх протокола TURN. Клиент извлекает временные TURN-учётки из ссылок на WebRTC-звонки и прозрачно маршрутизирует ваш VPN-трафик (WireGuard, AmneziaWG) до сервера на VPS, используя DTLS и мощные механизмы маскировки пакетов.
|
||||
**Free Turn Proxy** - универсальный прокси-туннель для инкапсуляции UDP/TCP трафика поверх протокола TURN. Клиент извлекает временные TURN-учётки из ссылок на WebRTC-звонки и прозрачно маршрутизирует ваш VPN-трафик (WireGuard, AmneziaWG, Xray/VLESS) до сервера на VPS, используя DTLS и механизмы маскировки пакетов.
|
||||
|
||||
## Разработка
|
||||
|
||||
|
||||
+56
-3
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/clientsdb"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/config"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/tcpserver"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/udpserver"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/dtlsdial"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire"
|
||||
@@ -129,6 +130,7 @@ func main() {
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
var backoff time.Duration
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -142,15 +144,53 @@ func main() {
|
||||
wg.Wait()
|
||||
return
|
||||
}
|
||||
logger.Warnf("accept: %v", err)
|
||||
// Отказ обычно устойчив (EMFILE): без паузы цикл сжёг бы ядро на ретраях.
|
||||
backoff = nextAcceptBackoff(backoff)
|
||||
logger.Warnf("accept: %v, retry in %s", err, backoff)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
wg.Wait()
|
||||
return
|
||||
case <-time.After(backoff):
|
||||
}
|
||||
continue
|
||||
}
|
||||
backoff = 0
|
||||
wg.Go(func() {
|
||||
handleAccepted(ctx, logger, db, conn, cfg)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
minAcceptBackoff = 5 * time.Millisecond
|
||||
maxAcceptBackoff = time.Second
|
||||
)
|
||||
|
||||
func nextAcceptBackoff(d time.Duration) time.Duration {
|
||||
if d <= 0 {
|
||||
return minAcceptBackoff
|
||||
}
|
||||
if d *= 2; d > maxAcceptBackoff {
|
||||
return maxAcceptBackoff
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func wireMode(m config.ProxyMode) byte {
|
||||
if m == config.ProxyModeTCP {
|
||||
return clientsdb.ModeTCP
|
||||
}
|
||||
return clientsdb.ModeUDP
|
||||
}
|
||||
|
||||
func modeName(b byte) string {
|
||||
if b == clientsdb.ModeTCP {
|
||||
return string(config.ProxyModeTCP)
|
||||
}
|
||||
return string(config.ProxyModeUDP)
|
||||
}
|
||||
|
||||
func handleAccepted(ctx context.Context, logger logx.Logger, db *clientsdb.DB, conn net.Conn, cfg *config.Server) {
|
||||
defer func() {
|
||||
if closeErr := conn.Close(); closeErr != nil {
|
||||
@@ -177,11 +217,20 @@ func handleAccepted(ctx context.Context, logger logx.Logger, db *clientsdb.DB, c
|
||||
logger.Debugf("Handshake done")
|
||||
|
||||
// Wire-контракт: клиент всегда передаёт Client ID первой app-record.
|
||||
clientID, err := clientsdb.ReadClientID(dtlsConn)
|
||||
clientID, clientMode, err := clientsdb.ReadClientID(dtlsConn)
|
||||
if err != nil {
|
||||
logger.Warnf("Read Client ID failed: %v", err)
|
||||
return
|
||||
}
|
||||
if want := wireMode(cfg.Proxy.Mode); clientMode != clientsdb.ModeUnset && clientMode != want {
|
||||
logger.Warnf("Mode mismatch from %s: клиент %s, сервер %s - трафик не пойдёт, приведите -mode к одному значению",
|
||||
conn.RemoteAddr(), modeName(clientMode), cfg.Proxy.Mode)
|
||||
return
|
||||
}
|
||||
if clientMode == clientsdb.ModeUnset && cfg.Proxy.Mode == config.ProxyModeTCP {
|
||||
logger.Warnf("Mode mismatch from %s: клиент без тега режима (udp), сервер tcp", conn.RemoteAddr())
|
||||
return
|
||||
}
|
||||
if db != nil {
|
||||
if !db.IsAuthorized(clientID) {
|
||||
logger.Warnf("Unauthorized Client ID: %s. Dropping connection.", clientID)
|
||||
@@ -193,7 +242,11 @@ func handleAccepted(ctx context.Context, logger logx.Logger, db *clientsdb.DB, c
|
||||
}
|
||||
|
||||
logger.Infof("Session up: client=%s from=%s", clientID, conn.RemoteAddr())
|
||||
udpserver.Handle(ctx, logger, conn, cfg.Proxy.Connect)
|
||||
if cfg.Proxy.Mode == config.ProxyModeTCP {
|
||||
tcpserver.Handle(ctx, logger, dtlsConn, cfg.Proxy.Connect, cfg.KCP.Profile)
|
||||
} else {
|
||||
udpserver.Handle(ctx, logger, conn, cfg.Proxy.Connect)
|
||||
}
|
||||
logger.Infof("Session down: client=%s from=%s", clientID, conn.RemoteAddr())
|
||||
}
|
||||
|
||||
|
||||
+3
-1
@@ -10,11 +10,13 @@ services:
|
||||
- path: .env
|
||||
required: false
|
||||
environment:
|
||||
# Backend address: WireGuard -> 127.0.0.1:51820
|
||||
# Backend address: WireGuard -> 127.0.0.1:51820 | Xray/sing-box -> 127.0.0.1:443
|
||||
CONNECT_ADDR: "127.0.0.1:51820"
|
||||
# LISTEN_ADDR: "0.0.0.0:56000"
|
||||
# MODE: "tcp" # tcp = TCP-форвардер для Xray/sing-box; default udp = WireGuard
|
||||
# OBF_PROFILE: "rtpopus" # none (default) | rtpopus
|
||||
# OBF_TIMING: "20ms" # межпакетная задержка для RTP-мимикрии; 0=выкл; только с OBF_PROFILE
|
||||
# KCP_INTERVAL / KCP_SNDWND / KCP_RCVWND / KCP_MTU / KCP_ACKNODELAY ... # тюнинг ARQ, только с MODE=tcp
|
||||
# OBF_KEY задаётся в .env (не коммитьте ключ в git)
|
||||
# CLIENTS_FILE: "/app/clients.json" # раскомментируйте для авторизации по Client ID
|
||||
# DEBUG: "false"
|
||||
|
||||
@@ -11,6 +11,21 @@ esac
|
||||
|
||||
set -- -listen "$LISTEN" -connect "$CONNECT"
|
||||
|
||||
if [ -n "${MODE}" ]; then
|
||||
set -- "$@" -mode "$MODE"
|
||||
fi
|
||||
|
||||
for kcp_var in NODELAY INTERVAL RESEND NC SNDWND RCVWND MTU ACKNODELAY; do
|
||||
eval "kcp_val=\${KCP_${kcp_var}}"
|
||||
if [ -n "${kcp_val}" ]; then
|
||||
kcp_flag="-kcp-$(echo "$kcp_var" | tr '[:upper:]' '[:lower:]')"
|
||||
case "$kcp_var" in
|
||||
ACKNODELAY) set -- "$@" "${kcp_flag}=${kcp_val}" ;;
|
||||
*) set -- "$@" "$kcp_flag" "$kcp_val" ;;
|
||||
esac
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -n "${OBF_PROFILE}" ] && [ "${OBF_PROFILE}" != "none" ]; then
|
||||
OBF="${OBF_KEY:?OBF_KEY is required when OBF_PROFILE != none}"
|
||||
set -- "$@" -obf-profile "$OBF_PROFILE" -obf-key "$OBF"
|
||||
|
||||
+7
-4
@@ -16,9 +16,9 @@ curl -fsSL https://raw.githubusercontent.com/samosvalishe/free-turn-proxy/master
|
||||
|
||||
**Неинтерактивный режим** (для автоматизации):
|
||||
```bash
|
||||
# Установка через Docker (порт бэкенда 51820)
|
||||
# Установка через Docker (UDP, порт бэкенда 51820)
|
||||
curl -fsSL https://raw.githubusercontent.com/samosvalishe/free-turn-proxy/master/scripts/install.sh | \
|
||||
sudo bash -s -- -y --method docker --backend-port 51820
|
||||
sudo bash -s -- -y --method docker --mode udp --backend-port 51820
|
||||
|
||||
# Обновление до конкретной версии
|
||||
sudo bash install.sh -y --update --version v1.2.3
|
||||
@@ -59,8 +59,9 @@ openssl rand -hex 32
|
||||
network_mode: "host" # Важно для доступа к локальному VPN (127.0.0.1)
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- CONNECT_ADDR=127.0.0.1:51820 # Порт ВАШЕГО VPN (WG/AmneziaWG)
|
||||
- CONNECT_ADDR=127.0.0.1:51820 # Порт ВАШЕГО VPN (WG/AmneziaWG/Xray)
|
||||
- LISTEN_ADDR=0.0.0.0:56000 # Внешний порт
|
||||
- MODE=udp # udp (WG/Amnezia) или tcp (Xray/VLESS)
|
||||
- OBF_PROFILE=rtpopus # Обязательная маскировка
|
||||
- OBF_KEY=<ВАШ_КЛЮЧ> # Ваш ключ
|
||||
# - CLIENTS_FILE=/opt/free-turn-proxy/clients.json # Для авторизации
|
||||
@@ -102,7 +103,7 @@ openssl rand -hex 32
|
||||
|
||||
## Настройка Файрвола
|
||||
|
||||
Откройте внешний порт (сервер слушает по **UDP**):
|
||||
Откройте внешний порт (сервер слушает по **UDP**, даже если `MODE=tcp`):
|
||||
```bash
|
||||
sudo ufw allow 56000/udp
|
||||
# Или iptables: sudo iptables -I INPUT -p udp --dport 56000 -j ACCEPT
|
||||
@@ -128,6 +129,8 @@ sudo ufw allow 56000/udp
|
||||
| --- | --- | --- |
|
||||
| `CONNECT_ADDR` | **обязательна** | IP и порт вашего VPN (бэкенда) |
|
||||
| `LISTEN_ADDR` | `0.0.0.0:56000` | Внешний адрес прослушивания |
|
||||
| `MODE` | `udp` | Режим туннеля: `udp` \| `tcp`; должен совпадать с клиентом |
|
||||
| `KCP_*` | из дефолта | Тюнинг ARQ при `MODE=tcp`: `KCP_NODELAY`, `KCP_INTERVAL`, `KCP_RESEND`, `KCP_NC`, `KCP_SNDWND`, `KCP_RCVWND`, `KCP_MTU`, `KCP_ACKNODELAY` |
|
||||
| `OBF_PROFILE` | `none` | Маскировка: `none` \| `rtpopus` \| `rtpopus2` |
|
||||
| `OBF_KEY` | пусто | Ключ маскировки |
|
||||
| `CLIENTS_FILE`| пусто | Путь к JSON-файлу авторизации |
|
||||
|
||||
+23
-4
@@ -4,18 +4,19 @@
|
||||
|
||||
| Флаг | По умолчанию | Описание |
|
||||
| --- | --- | --- |
|
||||
| `-listen` | `127.0.0.1:9000` | локальный адрес `ip:port`, куда подключается WireGuard-клиент |
|
||||
| `-listen` | `127.0.0.1:9000` | локальный адрес `ip:port`, куда подключается WireGuard (UDP) или Xray/sing-box (TCP) клиент |
|
||||
| `-peer` | **обязательный** | адрес сервера на VPS, `host:port` |
|
||||
| `-provider` | `vk` | источник TURN-creds: `vk` (см. `docs/providers.md`) |
|
||||
| `-link` | пусто | (устарел) одна ссылка VK Calls `https://vk.ru/call/join/...`; используйте `-links`. Игнорируется, если задан `-links` |
|
||||
| `-links` | **обязательный для `-provider vk`** (или `-link`) | ссылки VK Calls через запятую `https://vk.ru/call/join/A,https://vk.ru/call/join/B`; каждая даёт свой пул из `-n` стримов |
|
||||
| `-n` | `10` | параллельных TURN-потоков |
|
||||
| `-n` | `10` | параллельных TURN-потоков; в `-mode tcp` это число сессий пула, по которым round-robin раскладываются локальные TCP-соединения |
|
||||
| `-transport` | `tcp` | транспорт до TURN-реле: `tcp` (TCP/TLS) \| `udp` |
|
||||
| `-mode` | `udp` | режим туннеля: `udp` (UDP-релей для WireGuard) \| `tcp` (TCP-форвардер для Xray/sing-box) |
|
||||
| `-turn` | из creds | переопределить IP TURN-сервера |
|
||||
| `-port` | из creds | переопределить порт TURN-сервера |
|
||||
| `-obf-profile` | `none` | wire-профиль обфускации payload: `none` \| `rtpopus` (RTP/opus + ChaCha20-Poly1305 AEAD) \| `rtpopus2` (+ RTP header extension, ближе к WebRTC) \| `rtpopus3` (+ abs-send-time, VAD, имитация потерь, вариативный timestamp); должен совпадать с сервером |
|
||||
| `-obf-key` | пусто | общий ключ для `-obf-profile != none`, 32 байта hex (64 символа) |
|
||||
| `-obf-timing` | `0` | межпакетная задержка для RTP-мимикрии (напр. `20ms`); только с `-obf-profile != none`; `0` = выкл |
|
||||
| `-obf-timing` | `0` | межпакетная задержка для RTP-мимикрии (напр. `20ms`); только с `-obf-profile != none`; `0` = выкл. В `-mode tcp` особенно уместна: KCP гонит бёрсты полноразмерных пакетов, без выравнивания профиль на Opus не похож |
|
||||
| `-gen-obf-key` | `false` | напечатать новый ключ и выйти |
|
||||
| `-manual-captcha` | `false` | сразу ручной режим captcha (только `-provider vk`) |
|
||||
| `-streams-per-cred` | `10` | потоков на один кеш VK-учёток (только `-provider vk`) |
|
||||
@@ -26,12 +27,30 @@
|
||||
| `-sub` | пусто | URL подписки (sub.md) для получения списка серверов |
|
||||
| `-debug` | `false` | debug-логи |
|
||||
|
||||
## KCP (только `-mode tcp`, клиент и сервер)
|
||||
|
||||
Флаги настраивают ARQ-слой, который держит TCP-поток поверх датаграмм TURN. Задаются на каждой стороне отдельно; в `-mode udp` любое отличие от дефолта - ошибка запуска. В share-ссылке профиль едет полем `kcp`, так что гость получает тот же ARQ, что настроил владелец.
|
||||
|
||||
| Флаг | По умолчанию | Описание |
|
||||
| --- | --- | --- |
|
||||
| `-kcp-nodelay` | `1` | `0` (обычный) \| `1` (быстрый режим) |
|
||||
| `-kcp-interval` | `20` | интервал внутреннего цикла KCP, мс; больше = меньше служебного трафика |
|
||||
| `-kcp-resend` | `2` | быстрая повторная отправка после N дубликатов ACK; `0` = выкл |
|
||||
| `-kcp-nc` | `1` | congestion control: `0` (вкл) \| `1` (выкл) |
|
||||
| `-kcp-sndwnd` | `512` | окно отправки в пакетах |
|
||||
| `-kcp-rcvwnd` | `512` | окно приёма в пакетах |
|
||||
| `-kcp-mtu` | `1200` | MTU сегмента KCP, байты; допустимо `300..1350` |
|
||||
| `-kcp-acknodelay` | `true` | отправлять ACK сразу: ниже задержка, выше служебный трафик |
|
||||
|
||||
На мобильной сети дефолт заметно шумит; щадящий вариант - `-kcp-interval 40 -kcp-sndwnd 256 -kcp-rcvwnd 256 -kcp-acknodelay=false`.
|
||||
|
||||
## Сервер
|
||||
|
||||
| Флаг | По умолчанию | Описание |
|
||||
| --- | --- | --- |
|
||||
| `-listen` | `0.0.0.0:56000` | адрес прослушивания `ip:port` |
|
||||
| `-connect` | **обязательный** | локальный backend `host:port` (WG `127.0.0.1:51820`) |
|
||||
| `-connect` | **обязательный** | локальный backend `host:port` (WG `127.0.0.1:51820` / Xray `127.0.0.1:443`) |
|
||||
| `-mode` | `udp` | режим туннеля: `udp` \| `tcp`; должен совпадать с клиентом |
|
||||
| `-obf-profile` | `none` | wire-профиль обфускации payload: `none` \| `rtpopus` \| `rtpopus2` \| `rtpopus3`; должен совпадать с клиентом (описание профилей - в таблице клиента) |
|
||||
| `-obf-timing` | `0` | межпакетная задержка для RTP-мимикрии (напр. `10ms`); только с `-obf-profile != none`; `0` = выкл |
|
||||
| `-obf-key` | пусто | общий ключ для `-obf-profile != none`, 32 байта hex |
|
||||
|
||||
+19
-1
@@ -2,9 +2,27 @@
|
||||
|
||||
## UDP-Релей (WireGuard / AmneziaWG / Hysteria)
|
||||
|
||||
Клиент слушает локальный UDP-порт, сервер прозрачно форвардит UDP-пакеты в backend (например, WG `127.0.0.1:51820`).
|
||||
Дефолтный режим (`-mode udp`). Клиент слушает локальный UDP-порт, сервер прозрачно форвардит UDP-пакеты в backend (например, WG `127.0.0.1:51820`).
|
||||
Отлично подходит для VPN-протоколов, работающих поверх UDP: **WireGuard, AmneziaWG, Hysteria**.
|
||||
|
||||
## TCP-Форвардер (Xray / sing-box / VLESS)
|
||||
|
||||
Включается флагом `-mode tcp` на обеих сторонах. Сервер подключается к локальному TCP-бэкенду (например, Xray inbound `127.0.0.1:443`). Клиент слушает локальный TCP-порт, на который вы натравливаете свой Xray/v2rayN/sing-box.
|
||||
Подходит для TCP-прокси: **VLESS, VMess, Trojan, Shadowsocks**.
|
||||
|
||||
Relayed-данные TURN - всегда датаграммы, даже при `-transport tcp`, поэтому поверх DTLS трафик инкапсулируется через KCP (ARQ) + smux. Тюнинг ARQ - флаги `-kcp-*` (см. `docs/flags.md`).
|
||||
|
||||
```bash
|
||||
./server -listen 0.0.0.0:56000 -connect 127.0.0.1:443 -mode tcp
|
||||
./client -listen 127.0.0.1:9000 -peer <vps>:56000 -link "<vk-link>" -mode tcp
|
||||
```
|
||||
|
||||
`-n` в этом режиме задаёт число сессий пула: каждое локальное TCP-соединение уходит целиком в одну из них (round-robin).
|
||||
|
||||
Встроенный WireGuard (`-tunnel`) с `-mode tcp` не сочетается: он гонит датаграммы.
|
||||
|
||||
Режим должен совпадать на обеих сторонах: клиент помечает им первую запись, и сервер с другим `-mode` закрывает соединение с явной ошибкой вместо молчаливого зависания.
|
||||
|
||||
## OBF (wire-профили обфускации)
|
||||
|
||||
> [!WARNING]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Решение Проблем
|
||||
|
||||
- **Сначала запускайте client, потом включайте WireGuard.**
|
||||
- **Трафик не идет (нет интернета):** Проверьте серверный флаг `-connect`. В нем должен быть указан точный локальный порт, на котором слушает ваш VPN (например, `51820` для WG). Если порт не совпадает, прокси будет стучаться в пустоту.
|
||||
- **Сначала запускайте client, потом включайте WireGuard / Xray.**
|
||||
- **Трафик не идет (нет интернета):** Проверьте серверный флаг `-connect`. В нем должен быть указан точный локальный порт, на котором слушает ваш VPN (например, `51820` для WG или `443` для VLESS). Если порт не совпадает, прокси будет стучаться в пустоту.
|
||||
- **WireGuard забирает весь трафик:** пайп с `-debug 2>&1` и скриптом маршрутов обязателен (`scripts/routes.sh` / `scripts/routes.ps1` / `scripts/routes-macos.sh`). Маршруты не добавляются -> убедитесь, что в команде есть пайп перед скриптом.
|
||||
- **DPI блокирует UDP:** Если используете `-transport udp` и ничего не работает, попробуйте убрать флаг (использовать TCP по умолчанию).
|
||||
- **Обход шейпинга (кастомный TURN):** Если вы знаете "чистый" IP-адрес TURN-сервера VK, где нет агрессивного шейпинга, вы можете передать его вручную: `-turn <ip_address> -port <port>`. Это перезапишет данные, полученные из ссылки.
|
||||
|
||||
+7
-3
@@ -25,15 +25,17 @@ Payload - JSON-объект, закодированный `base64url` (без pa
|
||||
| `provider` | `-provider` | источник TURN-creds (например `vk`). |
|
||||
| `peer` | `-peer` | адрес сервера на VPS (`ip:port`). |
|
||||
| `transport` | `-transport` | транспорт до TURN-реле: `tcp` \| `udp`. |
|
||||
| `mode` | `-mode` | режим туннеля: `udp` \| `tcp`; отсутствует - `udp`. |
|
||||
| `obf` | `-obf-profile` | профиль обфускации (`rtpopus` \| `rtpopus2`); `none` опускается. |
|
||||
| `key` | `-obf-key` | ключ обфускации (hex), только при заданном `obf`. |
|
||||
| `n` | `-n` | число TURN-потоков. |
|
||||
| `spc` | `-streams-per-cred` | потоков на один кеш VK-учёток. |
|
||||
| `cid` | `-client-id` | Client ID гостя; owner добавляет его в allowlist (`clients.json`). |
|
||||
| `listen` | `-listen` | локальный `ip:port` для WireGuard. |
|
||||
| `listen` | `-listen` | локальный `ip:port` для WireGuard/Xray. |
|
||||
| `dns` | `-dns-mode` | резолвер клиента: `plain` \| `doh` \| `auto`. |
|
||||
| `dnss` | `-dns-servers` | свои DNS через запятую. |
|
||||
| `mcap` | `-manual-captcha` | ручная VK captcha (`true`). |
|
||||
| `kcp` | `-kcp-*` | профиль ARQ для `mode: tcp` (`nodelay`, `interval`, `resend`, `nc`, `sndwnd`, `rcvwnd`, `mtu`, `acknodelay`); отсутствует - дефолт. |
|
||||
| `name` | - | имя клиента / комментарий. |
|
||||
|
||||
> [!NOTE]
|
||||
@@ -45,7 +47,7 @@ Payload - JSON-объект, закодированный `base64url` (без pa
|
||||
### Пример (декодированный payload)
|
||||
|
||||
```json
|
||||
{"v":1,"provider":"vk","peer":"1.2.3.4:56000","transport":"tcp",
|
||||
{"v":1,"provider":"vk","peer":"1.2.3.4:56000","transport":"tcp","mode":"udp",
|
||||
"obf":"rtpopus","key":"d823fa...","n":10,"cid":"a1b2c3...","name":"RU-Server"}
|
||||
```
|
||||
|
||||
@@ -55,4 +57,6 @@ Payload - JSON-объект, закодированный `base64url` (без pa
|
||||
./client "freeturn://eyJ2IjoxLCJwcm92aWRlciI6InZrIiwicGVlciI6..." -link "https://vk.ru/call/join/..."
|
||||
```
|
||||
|
||||
Параметры из URI переопределяют базовые флаги (`-peer`, `-transport`, `-obf-key`, `-n` ...).
|
||||
Параметры из URI переопределяют базовые флаги (`-peer`, `-transport`, `-mode`, `-obf-key`, `-n` ...).
|
||||
|
||||
Версия ссылки не меняется: `mode` и `kcp` - опциональные поля, старый клиент их игнорирует и остаётся на `udp` с дефолтным ARQ.
|
||||
@@ -11,8 +11,11 @@ require (
|
||||
github.com/miekg/dns v1.1.72
|
||||
github.com/pion/dtls/v3 v3.1.5
|
||||
github.com/pion/logging v0.2.4
|
||||
github.com/pion/stun/v3 v3.1.6
|
||||
github.com/pion/transport/v4 v4.0.2
|
||||
github.com/pion/turn/v5 v5.0.12
|
||||
github.com/xtaci/kcp-go/v5 v5.6.72
|
||||
github.com/xtaci/smux v1.5.57
|
||||
golang.org/x/crypto v0.54.0
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20260723152544-d701c51f7e4e
|
||||
golang.org/x/net v0.57.0
|
||||
@@ -27,10 +30,13 @@ require (
|
||||
github.com/bogdanfinn/websocket v1.5.5-barnius // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/klauspost/compress v1.19.1 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.6 // indirect
|
||||
github.com/klauspost/reedsolomon v1.12.0 // indirect
|
||||
github.com/pion/randutil v0.1.0 // indirect
|
||||
github.com/pion/stun/v3 v3.1.6 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect
|
||||
github.com/tjfoc/gmsm v1.4.1 // indirect
|
||||
github.com/wlynxg/anet v0.0.5 // indirect
|
||||
golang.org/x/mobile v0.0.0-20260709172247-6129f5bee9d5 // indirect
|
||||
golang.org/x/mod v0.38.0 // indirect
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/amnezia-vpn/amneziawg-go v0.2.19 h1:l3rOmrA4o5z38kpgnA5iSk1yOm7Cv3AafIi4vxpSEV0=
|
||||
github.com/amnezia-vpn/amneziawg-go v0.2.19/go.mod h1:aMgOk9MuX0xI7b5TKAYp8pLM54RlXcOPzDvYw3YEO5A=
|
||||
github.com/andybalholm/brotli v1.2.2 h1:HzTuoo2ErYQqf5qvcJInB8uvqSVxRttzkFexPWtnceM=
|
||||
@@ -18,16 +20,41 @@ github.com/bogdanfinn/websocket v1.5.5-barnius h1:bY+qnxpai1qe7Jmjx+Sds/cmOSpuuL
|
||||
github.com/bogdanfinn/websocket v1.5.5-barnius/go.mod h1:gvvEw6pTKHb7yOiFvIfAFTStQWyrm25BMVCTj5wRSsI=
|
||||
github.com/cbeuw/connutil v1.0.1 h1:LWuNYjwm7JEDYG/ISAO1TfU4G+q2dA5NhR97eq2roCA=
|
||||
github.com/cbeuw/connutil v1.0.1/go.mod h1:lKofNtrW7Atmosgp1eNnTt2j2NjA2IkifapgLVI1QtA=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=
|
||||
github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc=
|
||||
github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/klauspost/reedsolomon v1.12.0 h1:I5FEp3xSwVCcEh3F5A7dofEfhXdF/bWhQWPH+XwBFno=
|
||||
github.com/klauspost/reedsolomon v1.12.0/go.mod h1:EPLZJeh4l27pUGC3aXOjheaoh1I9yut7xTURiW3LQ9Y=
|
||||
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
||||
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||
github.com/pion/dtls/v3 v3.1.5 h1:9xJtVsHwMYeSjPp5Hh1FTis4DchnQWtnOa5o+6ygqfc=
|
||||
@@ -42,55 +69,111 @@ github.com/pion/transport/v4 v4.0.2 h1:ifYlPqNwsy6aKQ9y8yzxXlHae5431ZrH2avkD/Rn6
|
||||
github.com/pion/transport/v4 v4.0.2/go.mod h1:06hFI+jCFcok2X2MekVufNZ/uzNZXivGBPfviSVcjgM=
|
||||
github.com/pion/turn/v5 v5.0.12 h1:6+b69ivQQXSlyfkp2AKripqD2k3W32qXK8QzCzpJWPI=
|
||||
github.com/pion/turn/v5 v5.0.12/go.mod h1:CQACsRDJtjQ+6RSrGHrS2PCIerLwbW3uqXRqOvtjAFg=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc=
|
||||
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5/go.mod h1:2JjD2zLQYH5HO74y5+aE3remJQvl6q4Sn6aWA2wD1Ng=
|
||||
github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho=
|
||||
github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE=
|
||||
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
|
||||
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
|
||||
github.com/xtaci/kcp-go/v5 v5.6.72 h1:FLaQPalgpufJYQRk0OK+gErEhXGLUPjv6FSRPrFR8Lk=
|
||||
github.com/xtaci/kcp-go/v5 v5.6.72/go.mod h1:9O3D8WR+cyyUjGiTILYfg17vn72otWuXK2AFfqIe6CM=
|
||||
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM=
|
||||
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae/go.mod h1:gXtu8J62kEgmN++bm9BVICuT/e8yiLI2KFobd/TRFsE=
|
||||
github.com/xtaci/smux v1.5.57 h1:N72VbGoSYxgcm6mPOYX0QzEZNVD3UI/JlVvAtXF+WrY=
|
||||
github.com/xtaci/smux v1.5.57/go.mod h1:IGQ9QYrBphmb/4aTnLEcJby0TNr3NV+OslIOMrX825Q=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
|
||||
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20260723152544-d701c51f7e4e h1:9TjMDOuGaMMTP5f7GXeHeA0JvFqGmv4DYRIWkzoePGI=
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20260723152544-d701c51f7e4e/go.mod h1:+UoQFNBq2p2wO+Q6ddVtYc25GZ6VNdOMyyrd4nrqrKs=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/mobile v0.0.0-20260709172247-6129f5bee9d5 h1:Mn1OzFmF0ZKX/ZayHz/UdnWHufPp1wlD9lZ5U8LRDFY=
|
||||
golang.org/x/mobile v0.0.0-20260709172247-6129f5bee9d5/go.mod h1:YX+n47s+53POxN3dx9cIGxG3hGUm/lD64hvrRJFbcSA=
|
||||
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
||||
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20211104170005-ce137452f963/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
||||
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||
golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM=
|
||||
golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
|
||||
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM=
|
||||
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
|
||||
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gvisor.dev/gvisor v0.0.0-20231202080848-1f7806d17489 h1:ze1vwAdliUAr68RQ5NtufWaXaOg8WUO2OACzEV+TNdE=
|
||||
gvisor.dev/gvisor v0.0.0-20231202080848-1f7806d17489/go.mod h1:10sU+Uh5KKNv1+2x2A0Gvzt8FjD3ASIhorV3YsauXhk=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
+24
-10
@@ -146,36 +146,50 @@ func (db *DB) save() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// WriteClientID отправляет Client ID (1 байт длины + строка).
|
||||
func WriteClientID(conn net.Conn, clientID string) error {
|
||||
// Тег режима едет хвостом той же записи: клиент до этого поля его не писал, а читатель
|
||||
// брал ровно 1+len байт - лишний байт старый сервер молча пропускает.
|
||||
const (
|
||||
ModeUnset byte = 0
|
||||
ModeUDP byte = 1
|
||||
ModeTCP byte = 2
|
||||
)
|
||||
|
||||
// WriteClientID отправляет Client ID (1 байт длины + строка + 1 байт режима).
|
||||
func WriteClientID(conn net.Conn, clientID string, mode byte) error {
|
||||
b := []byte(clientID)
|
||||
if len(b) > 255 {
|
||||
b = b[:255]
|
||||
}
|
||||
buf := make([]byte, 1+len(b))
|
||||
buf := make([]byte, 1+len(b)+1)
|
||||
buf[0] = byte(len(b)) //nolint:gosec // len(b) усечён до ≤255 выше
|
||||
copy(buf[1:], b)
|
||||
buf[1+len(b)] = mode
|
||||
_, err := conn.Write(buf)
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadClientID читает Client ID (1 байт длины + строка) из первой DTLS-записи.
|
||||
func ReadClientID(conn net.Conn) (string, error) {
|
||||
// ReadClientID читает Client ID из первой DTLS-записи. Режим ModeUnset - клиент старше
|
||||
// тега, режим у него всегда udp.
|
||||
func ReadClientID(conn net.Conn) (string, byte, error) {
|
||||
_ = conn.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||
defer func() { _ = conn.SetReadDeadline(time.Time{}) }()
|
||||
|
||||
buf := make([]byte, 256)
|
||||
buf := make([]byte, 257)
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", ModeUnset, err
|
||||
}
|
||||
if n == 0 {
|
||||
return "", nil
|
||||
return "", ModeUnset, nil
|
||||
}
|
||||
|
||||
l := int(buf[0])
|
||||
if n < 1+l {
|
||||
return "", io.ErrUnexpectedEOF
|
||||
return "", ModeUnset, io.ErrUnexpectedEOF
|
||||
}
|
||||
return string(buf[1 : 1+l]), nil
|
||||
mode := ModeUnset
|
||||
if n > 1+l {
|
||||
mode = buf[1+l]
|
||||
}
|
||||
return string(buf[1 : 1+l]), mode, nil
|
||||
}
|
||||
@@ -80,12 +80,12 @@ func TestClientIDRoundTrip(t *testing.T) {
|
||||
expectedID := "client-test-uuid-123"
|
||||
|
||||
go func() {
|
||||
if werr := WriteClientID(clientConn, expectedID); werr != nil {
|
||||
if werr := WriteClientID(clientConn, expectedID, ModeTCP); werr != nil {
|
||||
t.Errorf("WriteClientID failed: %v", werr)
|
||||
}
|
||||
}()
|
||||
|
||||
readID, err := ReadClientID(serverConn)
|
||||
readID, mode, err := ReadClientID(serverConn)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadClientID: %v", err)
|
||||
}
|
||||
@@ -93,4 +93,31 @@ func TestClientIDRoundTrip(t *testing.T) {
|
||||
if readID != expectedID {
|
||||
t.Errorf("expected %q, got %q", expectedID, readID)
|
||||
}
|
||||
if mode != ModeTCP {
|
||||
t.Errorf("mode = %d, want %d", mode, ModeTCP)
|
||||
}
|
||||
}
|
||||
|
||||
// Клиент старше тега режима слал ровно 1+len байт - такую запись читатель обязан принять.
|
||||
func TestReadClientIDLegacyRecordHasNoMode(t *testing.T) {
|
||||
clientConn, serverConn := net.Pipe()
|
||||
defer func() { _ = clientConn.Close() }()
|
||||
defer func() { _ = serverConn.Close() }()
|
||||
|
||||
const id = "legacy-client"
|
||||
go func() {
|
||||
buf := append([]byte{byte(len(id))}, id...) //nolint:gosec // длина константы заведомо ≤255
|
||||
_, _ = clientConn.Write(buf)
|
||||
}()
|
||||
|
||||
readID, mode, err := ReadClientID(serverConn)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadClientID: %v", err)
|
||||
}
|
||||
if readID != id {
|
||||
t.Errorf("id = %q, want %q", readID, id)
|
||||
}
|
||||
if mode != ModeUnset {
|
||||
t.Errorf("mode = %d, want ModeUnset", mode)
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,10 @@ func ClientArgs(c *Client) []string {
|
||||
if c.TURN.TransportUDP != def.TURN.TransportUDP {
|
||||
add("-transport", TransportUDP)
|
||||
}
|
||||
if c.Proxy.Mode != def.Proxy.Mode {
|
||||
add("-mode", string(c.Proxy.Mode))
|
||||
}
|
||||
args = append(args, kcpArgs(c.KCP.Profile, def.KCP.Profile)...)
|
||||
if c.Obf.Enabled() {
|
||||
add("-obf-profile", string(c.Obf.Profile))
|
||||
add("-obf-key", hex.EncodeToString(c.Obf.Key))
|
||||
|
||||
@@ -16,6 +16,8 @@ func TestClientArgsRoundTrip(t *testing.T) {
|
||||
}{
|
||||
{"minimal", validClientArgs()},
|
||||
{"udp transport", append(validClientArgs(), "-transport", "udp")},
|
||||
{"tcp mode", append(validClientArgs(), "-mode", "tcp")},
|
||||
{"tcp mode kcp", append(validClientArgs(), "-mode", "tcp", "-kcp-mtu", "900", "-kcp-interval", "40", "-kcp-acknodelay=false")},
|
||||
{"obf", append(validClientArgs(), "-obf-profile", "rtpopus3", "-obf-key", testObfKey)},
|
||||
{"obf timing", append(validClientArgs(), "-obf-profile", "rtpopus", "-obf-key", testObfKey, "-obf-timing", "20ms")},
|
||||
{"dns", append(validClientArgs(), "-dns-mode", "doh", "-dns-servers", "1.1.1.1,8.8.8.8:53")},
|
||||
|
||||
@@ -39,13 +39,14 @@ func ParseClient(args []string, errOut io.Writer) (*Client, error) {
|
||||
}
|
||||
fs.StringVar(&r.Turn, "turn", r.Turn, "IP TURN-сервера; override creds провайдера")
|
||||
fs.StringVar(&r.Port, "port", r.Port, "порт TURN-сервера; override creds провайдера")
|
||||
fs.StringVar(&r.Listen, "listen", r.Listen, "локальный ip:port для WireGuard-клиента")
|
||||
fs.StringVar(&r.Listen, "listen", r.Listen, "локальный ip:port для WireGuard/Xray клиента")
|
||||
fs.StringVar(&r.Provider, "provider", r.Provider, "источник TURN-creds: vk")
|
||||
fs.StringVar(&r.Link, "link", r.Link, "(устарел) одна ссылка VK Calls, используйте -links")
|
||||
fs.StringVar(&r.Links, "links", r.Links, "ссылки VK Calls через запятую: https://vk.ru/call/join/...,https://vk.ru/call/join/...")
|
||||
fs.StringVar(&r.Peer, "peer", r.Peer, "адрес сервера на VPS, host:port; обязательно")
|
||||
fs.IntVar(&r.N, "n", r.N, "число параллельных TURN-потоков")
|
||||
fs.StringVar(&r.Transport, "transport", r.Transport, "транспорт до TURN-реле: tcp | udp")
|
||||
fs.StringVar(&r.Mode, "mode", r.Mode, "режим туннеля: udp (WireGuard) | tcp (Xray/sing-box)")
|
||||
fs.StringVar(&r.ObfProfile, "obf-profile", r.ObfProfile, "wire-профиль обфускации: none | rtpopus | rtpopus2 | rtpopus3; должен совпадать с сервером")
|
||||
fs.StringVar(&r.ObfKey, "obf-key", r.ObfKey, "ключ для -obf-profile != none: 32 байта hex (64 символа)")
|
||||
fs.BoolVar(&r.GenObfKey, "gen-obf-key", r.GenObfKey, "напечатать новый -obf-key и выйти")
|
||||
@@ -59,6 +60,7 @@ func ParseClient(args []string, errOut io.Writer) (*Client, error) {
|
||||
fs.StringVar(&r.ClientID, "client-id", r.ClientID, "уникальный ID клиента (автогенерация если не задан)")
|
||||
fs.StringVar(&r.SubURL, "sub", r.SubURL, "URL подписки (sub.md) для получения списка серверов")
|
||||
fs.BoolVar(&r.Routes, "routes", r.Routes, "автоматическое управление маршрутами к TURN-серверам; требует прав администратора")
|
||||
kcp := registerKCPFlags(fs, r.KCP)
|
||||
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return nil, err
|
||||
@@ -71,6 +73,7 @@ func ParseClient(args []string, errOut io.Writer) (*Client, error) {
|
||||
}
|
||||
r.applyURI(u)
|
||||
}
|
||||
r.KCP = kcp.profile()
|
||||
|
||||
c, err := assemble(r)
|
||||
if err != nil {
|
||||
@@ -94,18 +97,26 @@ func ParseServer(args []string, errOut io.Writer) (*Server, error) {
|
||||
fs.SetOutput(errOut)
|
||||
}
|
||||
listen := fs.String("listen", def.Proxy.Listen, "локальный адрес прослушивания ip:port")
|
||||
connect := fs.String("connect", "", "локальный бэкенд host:port; обязательно: WG 127.0.0.1:51820")
|
||||
connect := fs.String("connect", "", "локальный бэкенд host:port; обязательно: WG 127.0.0.1:51820 | Xray 127.0.0.1:443")
|
||||
mode := fs.String("mode", string(def.Proxy.Mode), "режим туннеля: udp (WireGuard) | tcp (Xray/sing-box)")
|
||||
obfProfile := fs.String("obf-profile", string(def.Obf.Profile), "wire-профиль обфускации: none | rtpopus | rtpopus2 | rtpopus3; должен совпадать с клиентом")
|
||||
obfKey := fs.String("obf-key", "", "ключ для -obf-profile != none: 32 байта hex (64 символа)")
|
||||
genObfKey := fs.Bool("gen-obf-key", false, "напечатать новый -obf-key и выйти")
|
||||
obfTiming := fs.Duration("obf-timing", 0, "межпакетная задержка для RTP-мимикрии (напр. 10ms); 0=выкл")
|
||||
debug := fs.Bool("debug", false, "подробные debug-логи")
|
||||
clientsFile := fs.String("clients-file", "", "путь к файлу clients.json для авторизации по Client ID")
|
||||
kcp := registerKCPFlags(fs, def.KCP.Profile)
|
||||
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch *mode {
|
||||
case ModeUDP, ModeTCP:
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid -mode value %q: must be %s | %s", *mode, ModeUDP, ModeTCP)
|
||||
}
|
||||
|
||||
s := &Server{
|
||||
Obf: ObfOpts{
|
||||
Profile: ObfProfile(*obfProfile),
|
||||
@@ -113,10 +124,12 @@ func ParseServer(args []string, errOut io.Writer) (*Server, error) {
|
||||
Timing: *obfTiming,
|
||||
},
|
||||
Proxy: ProxyOpts{
|
||||
Mode: ProxyMode(*mode),
|
||||
Listen: *listen,
|
||||
Connect: *connect,
|
||||
},
|
||||
Log: LogOpts{Debug: *debug},
|
||||
KCP: KCPOpts{Profile: kcp.profile()},
|
||||
ClientsFile: *clientsFile,
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,16 @@ type ObfOpts struct {
|
||||
|
||||
func (o ObfOpts) Enabled() bool { return o.Profile != ObfProfileNone }
|
||||
|
||||
// ProxyMode задаёт тип прикладного трафика в TURN-туннеле.
|
||||
type ProxyMode string
|
||||
|
||||
const (
|
||||
ProxyModeUDP ProxyMode = "udp" // UDP-релей датаграмм (WireGuard)
|
||||
ProxyModeTCP ProxyMode = "tcp" // TCP-форвардер через KCP+smux (Xray/sing-box)
|
||||
)
|
||||
|
||||
type ProxyOpts struct {
|
||||
Mode ProxyMode
|
||||
Listen string
|
||||
Connect string
|
||||
Peer string
|
||||
@@ -87,6 +96,7 @@ type Client struct {
|
||||
VK VKOpts
|
||||
DNS DNSOpts
|
||||
Log LogOpts
|
||||
KCP KCPOpts
|
||||
Tunnel TunnelOpts
|
||||
ClientID string
|
||||
SubURL string
|
||||
@@ -97,5 +107,6 @@ type Server struct {
|
||||
Obf ObfOpts
|
||||
Proxy ProxyOpts
|
||||
Log LogOpts
|
||||
KCP KCPOpts
|
||||
ClientsFile string
|
||||
}
|
||||
@@ -313,9 +313,97 @@ func TestParseServer_GenObfKeySkipsConnectCheck(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseServer_RejectsRemovedModeFlag(t *testing.T) {
|
||||
_, err := ParseServer([]string{"-connect", "x:1", "-mode", "tcp"}, io.Discard)
|
||||
if err == nil {
|
||||
t.Error("expected error on removed -mode flag")
|
||||
func TestParseServer_ProxyMode(t *testing.T) {
|
||||
s, err := ParseServer([]string{"-connect", "x:1", "-mode", "tcp"}, io.Discard)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Proxy.Mode != ProxyModeTCP {
|
||||
t.Errorf("Proxy.Mode = %q, want %q", s.Proxy.Mode, ProxyModeTCP)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseServer_InvalidMode(t *testing.T) {
|
||||
_, err := ParseServer([]string{"-connect", "x:1", "-mode", "quic"}, io.Discard)
|
||||
if err == nil || !strings.Contains(err.Error(), "invalid -mode") {
|
||||
t.Errorf("expected mode error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseServer_KCPFlagsRequireTCPMode(t *testing.T) {
|
||||
_, err := ParseServer([]string{"-connect", "x:1", "-kcp-mtu", "900"}, io.Discard)
|
||||
if err == nil || !strings.Contains(err.Error(), "-kcp-*") {
|
||||
t.Errorf("expected kcp/mode error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseServer_KCPProfileApplied(t *testing.T) {
|
||||
s, err := ParseServer([]string{"-connect", "x:1", "-mode", "tcp", "-kcp-mtu", "900", "-kcp-interval", "40"}, io.Discard)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.KCP.Profile.MTU != 900 || s.KCP.Profile.Interval != 40 {
|
||||
t.Errorf("KCP profile = %+v", s.KCP.Profile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseServer_KCPMTUOutOfRange(t *testing.T) {
|
||||
_, err := ParseServer([]string{"-connect", "x:1", "-mode", "tcp", "-kcp-mtu", "2000"}, io.Discard)
|
||||
if err == nil || !strings.Contains(err.Error(), "-kcp-mtu") {
|
||||
t.Errorf("expected kcp-mtu error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClient_ProxyMode(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
want ProxyMode
|
||||
}{
|
||||
{"default-udp", nil, ProxyModeUDP},
|
||||
{"tcp", []string{"-mode", "tcp"}, ProxyModeTCP},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c, err := ParseClient(append(validClientArgs(), tc.args...), io.Discard)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.Proxy.Mode != tc.want {
|
||||
t.Errorf("Proxy.Mode = %q, want %q", c.Proxy.Mode, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClient_InvalidMode(t *testing.T) {
|
||||
_, err := ParseClient(append(validClientArgs(), "-mode", "quic"), io.Discard)
|
||||
if err == nil || !strings.Contains(err.Error(), "invalid -mode") {
|
||||
t.Errorf("expected mode error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClient_ObfTimingAllowedInTCP(t *testing.T) {
|
||||
args := append(validClientArgs(), "-mode", "tcp", "-obf-profile", "rtpopus3", "-obf-key", testObfKey, "-obf-timing", "20ms")
|
||||
c, err := ParseClient(args, io.Discard)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseClient() error = %v", err)
|
||||
}
|
||||
if c.Obf.Timing != 20*time.Millisecond {
|
||||
t.Errorf("Obf.Timing = %v, want 20ms", c.Obf.Timing)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClient_ObfTimingRequiresProfile(t *testing.T) {
|
||||
_, err := ParseClient(append(validClientArgs(), "-obf-timing", "20ms"), io.Discard)
|
||||
if err == nil || !strings.Contains(err.Error(), "-obf-timing") {
|
||||
t.Errorf("expected obf-timing/profile error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClient_KCPFlagsRequireTCPMode(t *testing.T) {
|
||||
_, err := ParseClient(append(validClientArgs(), "-kcp-sndwnd", "128"), io.Discard)
|
||||
if err == nil || !strings.Contains(err.Error(), "-kcp-*") {
|
||||
t.Errorf("expected kcp/mode error, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
package config
|
||||
|
||||
import "github.com/samosvalishe/free-turn-proxy/internal/tunnel"
|
||||
import (
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcpmux"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/tunnel"
|
||||
)
|
||||
|
||||
const (
|
||||
TransportTCP = "tcp"
|
||||
TransportUDP = "udp"
|
||||
|
||||
ModeUDP = "udp"
|
||||
ModeTCP = "tcp"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -18,6 +24,7 @@ const (
|
||||
DefaultStreams = 10
|
||||
DefaultStreamsPerCred = 10
|
||||
DefaultTransport = TransportTCP
|
||||
DefaultMode = ModeUDP
|
||||
DefaultDNSMode = DNSModeAuto
|
||||
DefaultProvider = ProviderVK
|
||||
DefaultPlatform = PlatformDesktop
|
||||
@@ -33,12 +40,14 @@ func defaultRaw() raw {
|
||||
N: DefaultStreams,
|
||||
StreamsPerCred: DefaultStreamsPerCred,
|
||||
Transport: DefaultTransport,
|
||||
Mode: DefaultMode,
|
||||
ObfProfile: string(DefaultObfProfile),
|
||||
Platform: string(DefaultPlatform),
|
||||
DNSMode: DefaultDNSMode,
|
||||
Routes: false,
|
||||
TunnelMode: string(tunnel.ModeNone),
|
||||
TunnelMTU: tunnel.DefaultMTU,
|
||||
KCP: kcpmux.DefaultProfile(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +64,7 @@ func Defaults() Client {
|
||||
func ServerDefaults() Server {
|
||||
return Server{
|
||||
Obf: ObfOpts{Profile: DefaultObfProfile},
|
||||
Proxy: ProxyOpts{Listen: DefaultServerListen},
|
||||
Proxy: ProxyOpts{Mode: ProxyModeUDP, Listen: DefaultServerListen},
|
||||
KCP: KCPOpts{Profile: kcpmux.DefaultProfile()},
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ type ClientJSON struct {
|
||||
Obf obfJSON `json:"obf"`
|
||||
DNS dnsJSON `json:"dns"`
|
||||
Log logJSON `json:"log"`
|
||||
KCP kcpJSON `json:"kcp"`
|
||||
Tunnel tunnelJSON `json:"tunnel"`
|
||||
}
|
||||
|
||||
@@ -42,6 +43,7 @@ type turnJSON struct {
|
||||
}
|
||||
|
||||
type proxyJSON struct {
|
||||
Mode string `json:"mode"`
|
||||
Listen string `json:"listen"`
|
||||
}
|
||||
|
||||
@@ -129,7 +131,8 @@ func defaultClientJSON() ClientJSON {
|
||||
Host: r.Turn,
|
||||
Port: r.Port,
|
||||
},
|
||||
Proxy: proxyJSON{Listen: r.Listen},
|
||||
Proxy: proxyJSON{Mode: r.Mode, Listen: r.Listen},
|
||||
KCP: kcpJSONFrom(r.KCP),
|
||||
VK: vkJSON{
|
||||
StreamsPerCred: r.StreamsPerCred,
|
||||
ManualCaptcha: r.ManualCaptcha,
|
||||
@@ -163,6 +166,7 @@ func (j ClientJSON) toRaw() raw {
|
||||
N: j.TURN.N,
|
||||
StreamsPerCred: j.VK.StreamsPerCred,
|
||||
Transport: j.TURN.Transport,
|
||||
Mode: j.Proxy.Mode,
|
||||
|
||||
ObfProfile: j.Obf.Profile,
|
||||
ObfKey: j.Obf.Key,
|
||||
@@ -182,5 +186,7 @@ func (j ClientJSON) toRaw() raw {
|
||||
TunnelMode: j.Tunnel.Mode,
|
||||
TunnelConfig: j.Tunnel.Config,
|
||||
TunnelMTU: j.Tunnel.MTU,
|
||||
|
||||
KCP: j.KCP.profile(),
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcpmux"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/uri"
|
||||
)
|
||||
|
||||
@@ -154,3 +155,29 @@ func TestClientJSONTimingMsMapsToDuration(t *testing.T) {
|
||||
t.Errorf("Obf.Timing = %v, want 25ms", c.Obf.Timing)
|
||||
}
|
||||
}
|
||||
|
||||
// Старый JSON без секций mode/kcp обязан читаться: поля optional, дефолт - udp.
|
||||
func TestParseClientJSONLegacyWithoutMode(t *testing.T) {
|
||||
data := `{"peer":"1.2.3.4:5000","vk":{"links":["abcdef"]}}`
|
||||
c, err := ParseClientJSON([]byte(data), "")
|
||||
if err != nil {
|
||||
t.Fatalf("ParseClientJSON() error = %v", err)
|
||||
}
|
||||
if c.Proxy.Mode != ProxyModeUDP {
|
||||
t.Errorf("Proxy.Mode = %q, want udp", c.Proxy.Mode)
|
||||
}
|
||||
if c.KCP.Profile != kcpmux.DefaultProfile() {
|
||||
t.Errorf("KCP profile = %+v, want default", c.KCP.Profile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClientJSONTCPMode(t *testing.T) {
|
||||
data := `{"peer":"1.2.3.4:5000","vk":{"links":["abcdef"]},"proxy":{"mode":"tcp"}}`
|
||||
c, err := ParseClientJSON([]byte(data), "")
|
||||
if err != nil {
|
||||
t.Fatalf("ParseClientJSON() error = %v", err)
|
||||
}
|
||||
if c.Proxy.Mode != ProxyModeTCP {
|
||||
t.Errorf("Proxy.Mode = %q, want tcp", c.Proxy.Mode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcpmux"
|
||||
)
|
||||
|
||||
// KCPOpts - параметры ARQ-слоя tcp-режима; в udp-режиме не используются.
|
||||
type KCPOpts struct {
|
||||
Profile kcpmux.Profile
|
||||
}
|
||||
|
||||
// kcpFlags держит указатели на -kcp-*; флаги регистрируются одинаково у клиента и
|
||||
// сервера, потому что окна и MTU настраиваются на каждой стороне отдельно.
|
||||
type kcpFlags struct {
|
||||
noDelay *int
|
||||
interval *int
|
||||
resend *int
|
||||
nc *int
|
||||
sndWnd *int
|
||||
rcvWnd *int
|
||||
mtu *int
|
||||
ackNoDelay *bool
|
||||
}
|
||||
|
||||
func registerKCPFlags(fs *flag.FlagSet, def kcpmux.Profile) *kcpFlags {
|
||||
return &kcpFlags{
|
||||
noDelay: fs.Int("kcp-nodelay", def.NoDelay, "KCP nodelay: 0 (обычный) | 1 (быстрый)"),
|
||||
interval: fs.Int("kcp-interval", def.Interval, "интервал внутреннего цикла KCP, мс; больше = меньше служебного трафика"),
|
||||
resend: fs.Int("kcp-resend", def.Resend, "быстрая повторная отправка после N дубликатов ACK; 0=выкл"),
|
||||
nc: fs.Int("kcp-nc", def.NC, "KCP congestion control: 0 (вкл) | 1 (выкл)"),
|
||||
sndWnd: fs.Int("kcp-sndwnd", def.SndWnd, "окно отправки KCP в пакетах"),
|
||||
rcvWnd: fs.Int("kcp-rcvwnd", def.RcvWnd, "окно приёма KCP в пакетах"),
|
||||
mtu: fs.Int("kcp-mtu", def.MTU, "MTU сегмента KCP в байтах"),
|
||||
ackNoDelay: fs.Bool("kcp-acknodelay", def.ACKNoDelay, "отправлять ACK сразу; ниже задержка, выше служебный трафик. Все -kcp-* работают только с -mode tcp"),
|
||||
}
|
||||
}
|
||||
|
||||
func (k *kcpFlags) profile() kcpmux.Profile {
|
||||
return kcpmux.Profile{
|
||||
NoDelay: *k.noDelay,
|
||||
Interval: *k.interval,
|
||||
Resend: *k.resend,
|
||||
NC: *k.nc,
|
||||
SndWnd: *k.sndWnd,
|
||||
RcvWnd: *k.rcvWnd,
|
||||
MTU: *k.mtu,
|
||||
ACKNoDelay: *k.ackNoDelay,
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
minKCPMTU = 300
|
||||
// Сегмент KCP едет внутри DTLS-записи (~37 B), obf-обёртки (до 40 B), TURN
|
||||
// ChannelData/Send (до 36 B) и IP/UDP (28 B): выше 1350 пакет режется по пути.
|
||||
maxKCPMTU = 1350
|
||||
)
|
||||
|
||||
func validateKCP(p kcpmux.Profile) error {
|
||||
if p.NoDelay != 0 && p.NoDelay != 1 {
|
||||
return fmt.Errorf("invalid -kcp-nodelay value %d: must be 0 | 1", p.NoDelay)
|
||||
}
|
||||
if p.NC != 0 && p.NC != 1 {
|
||||
return fmt.Errorf("invalid -kcp-nc value %d: must be 0 | 1", p.NC)
|
||||
}
|
||||
if p.Interval <= 0 {
|
||||
return fmt.Errorf("invalid -kcp-interval value %d: must be positive", p.Interval)
|
||||
}
|
||||
if p.Resend < 0 {
|
||||
return fmt.Errorf("invalid -kcp-resend value %d: must be non-negative", p.Resend)
|
||||
}
|
||||
if p.SndWnd <= 0 || p.RcvWnd <= 0 {
|
||||
return fmt.Errorf("invalid KCP window %d/%d: -kcp-sndwnd and -kcp-rcvwnd must be positive", p.SndWnd, p.RcvWnd)
|
||||
}
|
||||
if p.MTU < minKCPMTU || p.MTU > maxKCPMTU {
|
||||
return fmt.Errorf("invalid -kcp-mtu value %d: must be %d..%d", p.MTU, minKCPMTU, maxKCPMTU)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// kcpJSON - секция "kcp" клиентского JSON; в udp-режиме игнорируется.
|
||||
type kcpJSON struct {
|
||||
NoDelay int `json:"noDelay"`
|
||||
Interval int `json:"interval"`
|
||||
Resend int `json:"resend"`
|
||||
NC int `json:"nc"`
|
||||
SndWnd int `json:"sndWnd"`
|
||||
RcvWnd int `json:"rcvWnd"`
|
||||
MTU int `json:"mtu"`
|
||||
ACKNoDelay bool `json:"ackNoDelay"`
|
||||
}
|
||||
|
||||
func kcpJSONFrom(p kcpmux.Profile) kcpJSON {
|
||||
return kcpJSON{
|
||||
NoDelay: p.NoDelay,
|
||||
Interval: p.Interval,
|
||||
Resend: p.Resend,
|
||||
NC: p.NC,
|
||||
SndWnd: p.SndWnd,
|
||||
RcvWnd: p.RcvWnd,
|
||||
MTU: p.MTU,
|
||||
ACKNoDelay: p.ACKNoDelay,
|
||||
}
|
||||
}
|
||||
|
||||
func (k kcpJSON) profile() kcpmux.Profile {
|
||||
return kcpmux.Profile{
|
||||
NoDelay: k.NoDelay,
|
||||
Interval: k.Interval,
|
||||
Resend: k.Resend,
|
||||
NC: k.NC,
|
||||
SndWnd: k.SndWnd,
|
||||
RcvWnd: k.RcvWnd,
|
||||
MTU: k.MTU,
|
||||
ACKNoDelay: k.ACKNoDelay,
|
||||
}
|
||||
}
|
||||
|
||||
// kcpArgs выводит только отличия от дефолта: -kcp-* валидны лишь в tcp-режиме.
|
||||
func kcpArgs(p, def kcpmux.Profile) []string {
|
||||
var args []string
|
||||
addInt := func(flag string, v, d int) {
|
||||
if v != d {
|
||||
args = append(args, flag, strconv.Itoa(v))
|
||||
}
|
||||
}
|
||||
addInt("-kcp-nodelay", p.NoDelay, def.NoDelay)
|
||||
addInt("-kcp-interval", p.Interval, def.Interval)
|
||||
addInt("-kcp-resend", p.Resend, def.Resend)
|
||||
addInt("-kcp-nc", p.NC, def.NC)
|
||||
addInt("-kcp-sndwnd", p.SndWnd, def.SndWnd)
|
||||
addInt("-kcp-rcvwnd", p.RcvWnd, def.RcvWnd)
|
||||
addInt("-kcp-mtu", p.MTU, def.MTU)
|
||||
if p.ACKNoDelay != def.ACKNoDelay {
|
||||
args = append(args, "-kcp-acknodelay="+strconv.FormatBool(p.ACKNoDelay))
|
||||
}
|
||||
return args
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcpmux"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/tunnel"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/uri"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire/rtpopus"
|
||||
@@ -24,6 +25,7 @@ type raw struct {
|
||||
N int
|
||||
StreamsPerCred int
|
||||
Transport string
|
||||
Mode string
|
||||
|
||||
ObfProfile string
|
||||
ObfKey string
|
||||
@@ -44,6 +46,8 @@ type raw struct {
|
||||
TunnelMode string
|
||||
TunnelConfig string
|
||||
TunnelMTU int
|
||||
|
||||
KCP kcpmux.Profile
|
||||
}
|
||||
|
||||
// applyURI применяет параметры freeturn:// поверх raw-опций.
|
||||
@@ -54,6 +58,21 @@ func (r *raw) applyURI(u *uri.Config) {
|
||||
if u.Transport != "" {
|
||||
r.Transport = u.Transport
|
||||
}
|
||||
if u.Mode != "" {
|
||||
r.Mode = u.Mode
|
||||
}
|
||||
if u.KCP != nil {
|
||||
r.KCP = kcpmux.Profile{
|
||||
NoDelay: u.KCP.NoDelay,
|
||||
Interval: u.KCP.Interval,
|
||||
Resend: u.KCP.Resend,
|
||||
NC: u.KCP.NC,
|
||||
SndWnd: u.KCP.SndWnd,
|
||||
RcvWnd: u.KCP.RcvWnd,
|
||||
MTU: u.KCP.MTU,
|
||||
ACKNoDelay: u.KCP.ACKNoDelay,
|
||||
}
|
||||
}
|
||||
if u.N > 0 {
|
||||
r.N = u.N
|
||||
}
|
||||
@@ -92,6 +111,11 @@ func assemble(r raw) (*Client, error) {
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid -transport value %q: must be %s | %s", r.Transport, TransportTCP, TransportUDP)
|
||||
}
|
||||
switch r.Mode {
|
||||
case ModeUDP, ModeTCP:
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid -mode value %q: must be %s | %s", r.Mode, ModeUDP, ModeTCP)
|
||||
}
|
||||
n := r.N
|
||||
if n <= 0 {
|
||||
n = DefaultStreams
|
||||
@@ -118,6 +142,7 @@ func assemble(r raw) (*Client, error) {
|
||||
Timing: r.ObfTiming,
|
||||
},
|
||||
Proxy: ProxyOpts{
|
||||
Mode: ProxyMode(r.Mode),
|
||||
Listen: r.Listen,
|
||||
Peer: r.Peer,
|
||||
},
|
||||
@@ -130,6 +155,7 @@ func assemble(r raw) (*Client, error) {
|
||||
},
|
||||
DNS: DNSOpts{Mode: r.DNSMode},
|
||||
Log: LogOpts{Debug: r.Debug},
|
||||
KCP: KCPOpts{Profile: r.KCP},
|
||||
Tunnel: TunnelOpts{
|
||||
Mode: tunnel.Mode(r.TunnelMode),
|
||||
Config: r.TunnelConfig,
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcpmux"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/tunnel"
|
||||
)
|
||||
|
||||
@@ -43,13 +44,40 @@ func Validate(c *Client) error {
|
||||
if err := validateObfProfile(c.Obf.Profile); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateTunnel(c.Tunnel); err != nil {
|
||||
if err := validateProxyMode(c.Proxy.Mode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateTunnel(c.Tunnel, c.Proxy.Mode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateKCPFor(c.KCP, c.Proxy.Mode); err != nil {
|
||||
return err
|
||||
}
|
||||
return validateObfTiming(c.Obf)
|
||||
}
|
||||
|
||||
func validateTunnel(t TunnelOpts) error {
|
||||
func validateProxyMode(m ProxyMode) error {
|
||||
switch m {
|
||||
case ProxyModeUDP, ProxyModeTCP:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("invalid -mode value %q: must be %s | %s", m, ProxyModeUDP, ProxyModeTCP)
|
||||
}
|
||||
}
|
||||
|
||||
// validateKCPFor: -kcp-* настраивают ARQ, который живёт только в tcp-режиме.
|
||||
func validateKCPFor(k KCPOpts, mode ProxyMode) error {
|
||||
if mode != ProxyModeTCP {
|
||||
if k.Profile != kcpmux.DefaultProfile() {
|
||||
return errors.New("-kcp-* supported only with -mode tcp")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return validateKCP(k.Profile)
|
||||
}
|
||||
|
||||
// validateTunnel: встроенный WG гонит датаграммы, tcp-режим их не переносит.
|
||||
func validateTunnel(t TunnelOpts, mode ProxyMode) error {
|
||||
if t.Mode != "" && !t.Mode.Valid() {
|
||||
return fmt.Errorf("invalid tunnel mode %q: must be %s | %s | %s",
|
||||
t.Mode, tunnel.ModeNone, tunnel.ModeWG, tunnel.ModeAWG)
|
||||
@@ -57,6 +85,9 @@ func validateTunnel(t TunnelOpts) error {
|
||||
if !t.Enabled() {
|
||||
return nil
|
||||
}
|
||||
if mode != ProxyModeUDP {
|
||||
return errors.New("tunnel requires -mode udp")
|
||||
}
|
||||
if strings.TrimSpace(t.Config) == "" {
|
||||
return errors.New("tunnel config is required")
|
||||
}
|
||||
@@ -76,6 +107,12 @@ func ValidateServer(s *Server) error {
|
||||
if err := validateObfProfile(s.Obf.Profile); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateProxyMode(s.Proxy.Mode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateKCPFor(s.KCP, s.Proxy.Mode); err != nil {
|
||||
return err
|
||||
}
|
||||
return validateObfTiming(s.Obf)
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/tunnel"
|
||||
)
|
||||
|
||||
func validClient() *Client {
|
||||
@@ -69,3 +71,23 @@ func TestValidateServer(t *testing.T) {
|
||||
t.Fatal("ValidateServer() must reject unknown obf profile")
|
||||
}
|
||||
}
|
||||
|
||||
// Встроенный WG гонит датаграммы - в tcp-режиме такой конфиг молча не работал бы.
|
||||
func TestValidateTunnelRejectsTCPMode(t *testing.T) {
|
||||
c := validClient()
|
||||
c.Proxy.Mode = ProxyModeTCP
|
||||
c.Tunnel = TunnelOpts{Mode: tunnel.ModeWG, Config: "[Interface]", MTU: 1280}
|
||||
if err := Validate(c); err == nil || !strings.Contains(err.Error(), "tunnel requires") {
|
||||
t.Errorf("expected tunnel/mode error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Маршруты к TURN от режима туннеля не зависят.
|
||||
func TestValidateRoutesAllowedInTCPMode(t *testing.T) {
|
||||
c := validClient()
|
||||
c.Proxy.Mode = ProxyModeTCP
|
||||
c.Routes = true
|
||||
if err := Validate(c); err != nil {
|
||||
t.Errorf("routes must be allowed in tcp mode: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package netconn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// BiCopy закрывает оба conn, как только копирование в любую сторону завершится.
|
||||
func BiCopy(ctx context.Context, c1, c2 net.Conn, errf func(format string, v ...any)) (int64, int64) {
|
||||
ctx2, cancel := context.WithCancel(ctx)
|
||||
setDeadline := func(t time.Time, what string) {
|
||||
if err := c1.SetDeadline(t); err != nil && errf != nil {
|
||||
errf("BiCopy: c1 %s: %v", what, err)
|
||||
}
|
||||
if err := c2.SetDeadline(t); err != nil && errf != nil {
|
||||
errf("BiCopy: c2 %s: %v", what, err)
|
||||
}
|
||||
}
|
||||
hookDone := make(chan struct{})
|
||||
stopOnCancel := context.AfterFunc(ctx2, func() {
|
||||
defer close(hookDone)
|
||||
setDeadline(time.Now(), "SetDeadline")
|
||||
})
|
||||
|
||||
var wg sync.WaitGroup
|
||||
var c1FromC2, c2FromC1 int64
|
||||
wg.Go(func() {
|
||||
defer cancel()
|
||||
n, err := io.Copy(c1, c2)
|
||||
c1FromC2 = n
|
||||
if err != nil && errf != nil {
|
||||
errf("BiCopy: c1<-c2: %v", err)
|
||||
}
|
||||
})
|
||||
wg.Go(func() {
|
||||
defer cancel()
|
||||
n, err := io.Copy(c2, c1)
|
||||
c2FromC1 = n
|
||||
if err != nil && errf != nil {
|
||||
errf("BiCopy: c2<-c1: %v", err)
|
||||
}
|
||||
})
|
||||
wg.Wait()
|
||||
|
||||
// Дедлайны сбрасываются только после того, как хук отменён или доработал - иначе
|
||||
// он взвёлся бы следом и оставил conn'ы просроченными навсегда.
|
||||
if !stopOnCancel() {
|
||||
<-hookDone
|
||||
}
|
||||
setDeadline(time.Time{}, "clear deadline")
|
||||
return c1FromC2, c2FromC1
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package netconn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBiCopy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
a1, a2 := net.Pipe()
|
||||
b1, b2 := net.Pipe()
|
||||
defer func() { _ = a1.Close() }()
|
||||
defer func() { _ = b1.Close() }()
|
||||
|
||||
done := make(chan [2]int64, 1)
|
||||
go func() {
|
||||
n1, n2 := BiCopy(context.Background(), a2, b2, nil)
|
||||
done <- [2]int64{n1, n2}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
_, _ = a1.Write([]byte("ping"))
|
||||
_ = a1.Close()
|
||||
}()
|
||||
|
||||
got := make([]byte, 4)
|
||||
if _, err := io.ReadFull(b1, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != "ping" {
|
||||
t.Fatalf("got %q, want %q", got, "ping")
|
||||
}
|
||||
_ = b1.Close()
|
||||
|
||||
counts := <-done
|
||||
if counts[1] != 4 {
|
||||
t.Errorf("a2->b2 = %d, want 4", counts[1])
|
||||
}
|
||||
}
|
||||
@@ -158,3 +158,24 @@ func (p *packetPipe) SetReadDeadline(t time.Time) error {
|
||||
|
||||
// SetWriteDeadline - no-op: неблокирующая запись дропает пакет при переполнении очереди.
|
||||
func (*packetPipe) SetWriteDeadline(time.Time) error { return nil }
|
||||
|
||||
// datagramConn подаёт packetPipe как net.Conn: границы датаграмм сохраняются, поэтому
|
||||
// поверх такой пары можно поднимать KCP без реального сокета.
|
||||
type datagramConn struct {
|
||||
net.PacketConn
|
||||
remote net.Addr
|
||||
}
|
||||
|
||||
func (c *datagramConn) Read(b []byte) (int, error) {
|
||||
n, _, err := c.ReadFrom(b)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (c *datagramConn) Write(b []byte) (int, error) { return c.WriteTo(b, c.remote) }
|
||||
func (c *datagramConn) RemoteAddr() net.Addr { return c.remote }
|
||||
|
||||
// DatagramPipe - пара связанных net.Conn в памяти с датаграммной семантикой.
|
||||
func DatagramPipe(mtu, queue int) (net.Conn, net.Conn) {
|
||||
a, b := PacketPipe(mtu, queue)
|
||||
return &datagramConn{PacketConn: a, remote: b.LocalAddr()}, &datagramConn{PacketConn: b, remote: a.LocalAddr()}
|
||||
}
|
||||
@@ -409,13 +409,20 @@ func (s *captchaSession) fetchCaptchaHTML(redirectURI string) (string, error) {
|
||||
}
|
||||
|
||||
func parseCaptchaPage(html string) (*captchaPage, error) {
|
||||
// Заглушка VK (429/5xx) - временно; поломка парсера на настоящей странице - нет,
|
||||
// её надо эскалировать на следующий режим решения, а не ретраить вечно. Отличаем
|
||||
// по серверным глобалам: PoW-скрипт обфусцирован, переименование его конверта -
|
||||
// это поломка парсера, а не отсутствие страницы.
|
||||
if !reCaptchaVKGlobal.MatchString(html) && !reCaptchaInitGlobal.MatchString(html) {
|
||||
return nil, fmt.Errorf("%w: not a captcha page (bytes=%d)", ErrUnavailable, len(html))
|
||||
}
|
||||
pow, err := parsePowParams(html)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
return nil, err
|
||||
}
|
||||
debugInfo := parseCaptchaDebugInfo(html)
|
||||
if debugInfo == "" {
|
||||
return nil, fmt.Errorf("%w: captcha debug_info not found on page", ErrUnavailable)
|
||||
return nil, errors.New("captcha debug_info not found on page")
|
||||
}
|
||||
return &captchaPage{Pow: pow, DebugInfo: debugInfo, Init: parseCaptchaInitGlobal(html)}, nil
|
||||
}
|
||||
|
||||
@@ -278,3 +278,18 @@ func TestParseCaptchaPageRejectsNonCaptchaHTML(t *testing.T) {
|
||||
t.Fatalf("err = %v, want ErrUnavailable", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Смена обфускации - не аутаж: ошибка обязана дойти до эскалации на другой решатель.
|
||||
// Переименованный конверт PoW - именно этот случай, страница настоящая.
|
||||
func TestParseCaptchaPageBrokenParserIsNotUnavailable(t *testing.T) {
|
||||
t.Parallel()
|
||||
for name, html := range map[string]string{
|
||||
"pow renamed": `<script>window.vk = {}; window.zzz = "v2." + solve();</script>`,
|
||||
"debug absent": `<script>window.init = {};</script>`,
|
||||
} {
|
||||
_, err := parseCaptchaPage(html)
|
||||
if err == nil || errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("%s: err = %v, want plain parse error", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,12 +17,14 @@ import (
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/provider/vk/internal/browserprofile"
|
||||
)
|
||||
|
||||
const powResultGlobal = "captchaPowResult"
|
||||
|
||||
// PoW-скрипт страницы обфусцирован, имена переменных генерируются заново на каждый
|
||||
// релиз. Стабильны только аргументы IIFE (input, difficulty, метка ошибки) и
|
||||
// префикс версии конверта.
|
||||
var (
|
||||
rePowArgs = regexp.MustCompile(`\}\(\s*["']([A-Za-z0-9_-]{8,})["']\s*,\s*(\d+)\s*,\s*["'][^"']*["']\s*\)\s*\)`)
|
||||
rePowPrefix = regexp.MustCompile(`captchaPowResult["'\]]{0,3}\s*=\s*["']([A-Za-z0-9._-]{0,8})["']\s*\+`)
|
||||
rePowPrefix = regexp.MustCompile(powResultGlobal + `["'\]]{0,3}\s*=\s*["']([A-Za-z0-9._-]{0,8})["']\s*\+`)
|
||||
)
|
||||
|
||||
type powParams struct {
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
package vkauth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/pion/stun/v3"
|
||||
)
|
||||
|
||||
type StreamCredentialsCache struct {
|
||||
@@ -75,11 +78,22 @@ func IsAuthError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
// Ответ TURN-сервера приходит типизированным - код берём из него, а не из текста.
|
||||
if turnErr, ok := errors.AsType[*stun.TurnError](err); ok {
|
||||
switch turnErr.ErrorCodeAttr.Code {
|
||||
// 486 - квота аллокаций: креды живы, но новую сессию по ним не поднять.
|
||||
case stun.CodeUnauthorized, stun.CodeWrongCredentials,
|
||||
stun.CodeStaleNonce, stun.CodeAllocQuotaReached:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
// Ошибки не от TURN-сервера (получение кредов у провайдера) типа не несут.
|
||||
s := err.Error()
|
||||
return strings.Contains(s, "401") ||
|
||||
strings.Contains(s, "Unauthorized") ||
|
||||
strings.Contains(s, "authentication") ||
|
||||
strings.Contains(s, "invalid credential") ||
|
||||
strings.Contains(s, "stale nonce") ||
|
||||
strings.Contains(s, "Allocation Quota")
|
||||
strings.Contains(s, "stale nonce")
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
tlsclient "github.com/bogdanfinn/tls-client"
|
||||
"github.com/pion/stun/v3"
|
||||
)
|
||||
|
||||
// newTestClient builds a Client with a zero-interval throttle and the supplied
|
||||
@@ -36,7 +37,6 @@ func TestIsAuthError(t *testing.T) {
|
||||
"stale nonce": true,
|
||||
"invalid credential": true,
|
||||
"authentication required": true,
|
||||
"486: Allocation Quota Reached": true,
|
||||
"connection refused": false,
|
||||
"dial tcp 10.0.0.1:48612: i/o timeout": false,
|
||||
"": false,
|
||||
@@ -52,6 +52,28 @@ func TestIsAuthError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsAuthErrorTurnCode(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
codes := map[stun.ErrorCode]bool{
|
||||
stun.CodeAllocQuotaReached: true,
|
||||
stun.CodeUnauthorized: true,
|
||||
stun.CodeStaleNonce: true,
|
||||
stun.CodeWrongCredentials: true,
|
||||
stun.CodeInsufficientCapacity: false,
|
||||
stun.CodeForbidden: false,
|
||||
}
|
||||
for code, want := range codes {
|
||||
err := fmt.Errorf("TURN allocate: %w", &stun.TurnError{
|
||||
StunMessageType: stun.NewType(stun.MethodAllocate, stun.ClassErrorResponse),
|
||||
ErrorCodeAttr: stun.ErrorCodeAttribute{Code: code, Reason: []byte("reason")},
|
||||
})
|
||||
if got := IsAuthError(err); got != want {
|
||||
t.Errorf("IsAuthError(code %d) = %v, want %v", code, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreCacheGrouping(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// Package allocpace распределяет во времени вызовы TURN Allocate: квота считается на
|
||||
// username, поэтому залп от всех потоков сразу упирается в неё плотнее, чем очередь.
|
||||
package allocpace
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const DefaultInterval = 200 * time.Millisecond
|
||||
|
||||
type Pacer struct {
|
||||
mu sync.Mutex
|
||||
next time.Time
|
||||
step time.Duration
|
||||
}
|
||||
|
||||
func New(step time.Duration) *Pacer {
|
||||
return &Pacer{step: step}
|
||||
}
|
||||
|
||||
// Wait возвращает false, только если ctx отменён - слот всё равно занят и не переиспользуется.
|
||||
func (p *Pacer) Wait(ctx context.Context) bool {
|
||||
if p == nil {
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
wait := time.Until(p.slot())
|
||||
if wait <= 0 {
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
t := time.NewTimer(wait)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Pacer) slot() time.Time {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
now := time.Now()
|
||||
if p.next.Before(now) {
|
||||
p.next = now
|
||||
}
|
||||
slot := p.next
|
||||
p.next = slot.Add(p.step)
|
||||
return slot
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package udprelay
|
||||
package allocpace
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -15,14 +15,14 @@ func TestAllocPacerSpacesConcurrentWaiters(t *testing.T) {
|
||||
waiters = 5
|
||||
slowdown = 3
|
||||
)
|
||||
p := newAllocPacer(step)
|
||||
p := New(step)
|
||||
|
||||
start := time.Now()
|
||||
var wg sync.WaitGroup
|
||||
elapsed := make([]time.Duration, waiters)
|
||||
for i := range waiters {
|
||||
wg.Go(func() {
|
||||
if !p.wait(context.Background()) {
|
||||
if !p.Wait(context.Background()) {
|
||||
t.Errorf("waiter %d: wait returned false", i)
|
||||
return
|
||||
}
|
||||
@@ -46,10 +46,10 @@ func TestAllocPacerSpacesConcurrentWaiters(t *testing.T) {
|
||||
// Первый в очереди не платит ничего: рецикл одинокого стрима не должен ждать шаг.
|
||||
func TestAllocPacerFirstSlotIsFree(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newAllocPacer(time.Second)
|
||||
p := New(time.Second)
|
||||
|
||||
start := time.Now()
|
||||
if !p.wait(context.Background()) {
|
||||
if !p.Wait(context.Background()) {
|
||||
t.Fatal("wait returned false")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 100*time.Millisecond {
|
||||
@@ -59,7 +59,7 @@ func TestAllocPacerFirstSlotIsFree(t *testing.T) {
|
||||
|
||||
func TestAllocPacerWaitReturnsFalseOnCancel(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newAllocPacer(time.Hour)
|
||||
p := New(time.Hour)
|
||||
p.slot() // занять первый слот, следующий уедет на час
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
@@ -67,7 +67,7 @@ func TestAllocPacerWaitReturnsFalseOnCancel(t *testing.T) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
cancel()
|
||||
}()
|
||||
if p.wait(ctx) {
|
||||
if p.Wait(ctx) {
|
||||
t.Fatal("wait returned true on cancelled context")
|
||||
}
|
||||
}
|
||||
@@ -75,13 +75,13 @@ func TestAllocPacerWaitReturnsFalseOnCancel(t *testing.T) {
|
||||
// Nil-приёмник допустим: Deps собирают и в обход Run.
|
||||
func TestAllocPacerNilIsPassthrough(t *testing.T) {
|
||||
t.Parallel()
|
||||
var p *allocPacer
|
||||
if !p.wait(context.Background()) {
|
||||
var p *Pacer
|
||||
if !p.Wait(context.Background()) {
|
||||
t.Fatal("nil pacer must pass through")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if p.wait(ctx) {
|
||||
if p.Wait(ctx) {
|
||||
t.Fatal("nil pacer must respect cancelled context")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package tcprelay
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/netconn"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/tcpserver"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcpmux"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
func echoBackend(t *testing.T) string {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0") //nolint:noctx // тестовый сокет
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
|
||||
go func() {
|
||||
for {
|
||||
conn, aerr := ln.Accept()
|
||||
if aerr != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer func() { _ = conn.Close() }()
|
||||
_, _ = io.Copy(conn, conn)
|
||||
}()
|
||||
}
|
||||
}()
|
||||
return ln.Addr().String()
|
||||
}
|
||||
|
||||
// pairedSession поднимает клиентскую smux-сессию против tcpserver.Handle через пару
|
||||
// в памяти: TURN и DTLS в этом тесте не участвуют, проверяется слой tcprelay<->tcpserver.
|
||||
func pairedSession(t *testing.T, ctx context.Context, backendAddr string) *smux.Session {
|
||||
t.Helper()
|
||||
clientConn, serverConn := netconn.DatagramPipe(2048, 1024)
|
||||
t.Cleanup(func() { _ = clientConn.Close(); _ = serverConn.Close() })
|
||||
|
||||
go tcpserver.Handle(ctx, logx.Nop(), serverConn, backendAddr, kcpmux.DefaultProfile())
|
||||
|
||||
kcpSess, err := kcpmux.Dial(clientConn, kcpmux.DefaultProfile())
|
||||
if err != nil {
|
||||
t.Fatalf("kcp dial: %v", err)
|
||||
}
|
||||
sess, err := smux.Client(kcpSess, kcpmux.SmuxConfig())
|
||||
if err != nil {
|
||||
t.Fatalf("smux client: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sess.Close() })
|
||||
return sess
|
||||
}
|
||||
|
||||
func TestAcceptLoopForwardsToBackend(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
backendAddr := echoBackend(t)
|
||||
|
||||
var active atomic.Int32
|
||||
pool := newSessionPool(&active)
|
||||
pool.Add(1, pairedSession(t, ctx, backendAddr), nil)
|
||||
pool.Add(2, pairedSession(t, ctx, backendAddr), nil)
|
||||
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0") //nolint:noctx // тестовый сокет
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = listener.Close() }()
|
||||
|
||||
deps := &Deps{Log: logx.Nop(), ConnectedStreams: &active}
|
||||
loopDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(loopDone)
|
||||
acceptLoop(ctx, deps, listener, pool)
|
||||
}()
|
||||
|
||||
// По соединению на каждую сессию пула: round-robin должен развести их без потерь.
|
||||
for i := range 4 {
|
||||
conn, derr := net.Dial("tcp", listener.Addr().String()) //nolint:noctx // тестовый сокет
|
||||
if derr != nil {
|
||||
t.Fatalf("dial %d: %v", i, derr)
|
||||
}
|
||||
payload := bytes.Repeat([]byte{byte('a' + i)}, 32*1024)
|
||||
go func() { _, _ = conn.Write(payload) }()
|
||||
|
||||
got := make([]byte, len(payload))
|
||||
if serr := conn.SetReadDeadline(time.Now().Add(30 * time.Second)); serr != nil {
|
||||
t.Fatal(serr)
|
||||
}
|
||||
if _, rerr := io.ReadFull(conn, got); rerr != nil {
|
||||
t.Fatalf("conn %d read: %v", i, rerr)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatalf("conn %d: echo mismatch", i)
|
||||
}
|
||||
_ = conn.Close()
|
||||
}
|
||||
|
||||
cancel()
|
||||
_ = listener.Close()
|
||||
select {
|
||||
case <-loopDone:
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("acceptLoop did not return after cancel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptLoopRejectsWithoutSessions(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0") //nolint:noctx // тестовый сокет
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = listener.Close() }()
|
||||
|
||||
pool := newSessionPool(nil)
|
||||
go acceptLoop(ctx, &Deps{Log: logx.Nop()}, listener, pool)
|
||||
|
||||
conn, err := net.Dial("tcp", listener.Addr().String()) //nolint:noctx // тестовый сокет
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
|
||||
if derr := conn.SetReadDeadline(time.Now().Add(10 * time.Second)); derr != nil {
|
||||
t.Fatal(derr)
|
||||
}
|
||||
if _, rerr := conn.Read(make([]byte, 1)); rerr == nil {
|
||||
t.Error("connection must be rejected when pool is empty")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// Package tcprelay реализует tcp-режим клиента: локальный TCP-listener, а каждое
|
||||
// принятое соединение уходит отдельным smux-потоком в одну из сессий пула
|
||||
// TURN+DTLS+KCP+smux (round-robin).
|
||||
package tcprelay
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/stats"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// pooledSession - одна сессия TURN+DTLS+KCP+smux.
|
||||
type pooledSession struct {
|
||||
id int
|
||||
sess *smux.Session
|
||||
traffic *stats.Stats
|
||||
active atomic.Int32
|
||||
}
|
||||
|
||||
// sessionPool - конкурентно-безопасный round-robin пул живых сессий.
|
||||
type sessionPool struct {
|
||||
mu sync.RWMutex
|
||||
sessions []*pooledSession
|
||||
counter atomic.Uint64
|
||||
connID atomic.Uint64
|
||||
|
||||
// active - зеркало числа живых сессий для UI (те же "N/M", что и в udp-режиме).
|
||||
active *atomic.Int32
|
||||
|
||||
readyOnce sync.Once
|
||||
ready chan struct{}
|
||||
}
|
||||
|
||||
func newSessionPool(active *atomic.Int32) *sessionPool {
|
||||
return &sessionPool{active: active, ready: make(chan struct{})}
|
||||
}
|
||||
|
||||
// publishActive вызывать под p.mu.
|
||||
func (p *sessionPool) publishActive() {
|
||||
if p.active != nil {
|
||||
p.active.Store(int32(len(p.sessions))) //nolint:gosec // сессий десятки, int32 не переполнить
|
||||
}
|
||||
}
|
||||
|
||||
// Ready закрывается на первой поднявшейся сессии.
|
||||
func (p *sessionPool) Ready() <-chan struct{} { return p.ready }
|
||||
|
||||
func (p *sessionPool) Add(id int, s *smux.Session, traffic *stats.Stats) *pooledSession {
|
||||
ps := &pooledSession{id: id, sess: s, traffic: traffic}
|
||||
p.mu.Lock()
|
||||
p.sessions = append(p.sessions, ps)
|
||||
p.publishActive()
|
||||
p.mu.Unlock()
|
||||
p.readyOnce.Do(func() { close(p.ready) })
|
||||
return ps
|
||||
}
|
||||
|
||||
// Remove no-op, если ps не найден.
|
||||
func (p *sessionPool) Remove(ps *pooledSession) {
|
||||
p.mu.Lock()
|
||||
for i, s := range p.sessions {
|
||||
if s == ps {
|
||||
p.sessions = append(p.sessions[:i], p.sessions[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
p.publishActive()
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
// Pick - nil, если живых сессий нет.
|
||||
func (p *sessionPool) Pick() *pooledSession {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
n := len(p.sessions)
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
for range n {
|
||||
ps := p.sessions[(p.counter.Add(1)-1)%uint64(n)]
|
||||
if !ps.sess.IsClosed() {
|
||||
return ps
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *sessionPool) NextConnID() uint64 { return p.connID.Add(1) }
|
||||
|
||||
func (p *sessionPool) Count() int {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
return len(p.sessions)
|
||||
}
|
||||
|
||||
// CloseAll рвёт сессии, не трогая listener: рецикл не должен ронять локальный порт.
|
||||
func (p *sessionPool) CloseAll() {
|
||||
p.mu.RLock()
|
||||
snapshot := make([]*pooledSession, len(p.sessions))
|
||||
copy(snapshot, p.sessions)
|
||||
p.mu.RUnlock()
|
||||
for _, ps := range snapshot {
|
||||
_ = ps.sess.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package tcprelay
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/netconn"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcpmux"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// fakeSession - живая smux-сессия поверх пары в памяти; закрытие видно через IsClosed.
|
||||
func fakeSession(t *testing.T) *smux.Session {
|
||||
t.Helper()
|
||||
a, b := netconn.DatagramPipe(2048, 64)
|
||||
t.Cleanup(func() { _ = a.Close(); _ = b.Close() })
|
||||
|
||||
kcpSess, err := kcpmux.Dial(a, kcpmux.DefaultProfile())
|
||||
if err != nil {
|
||||
t.Fatalf("kcp dial: %v", err)
|
||||
}
|
||||
sess, err := smux.Client(kcpSess, kcpmux.SmuxConfig())
|
||||
if err != nil {
|
||||
t.Fatalf("smux client: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sess.Close() })
|
||||
return sess
|
||||
}
|
||||
|
||||
func TestPoolPickRoundRobin(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var active atomic.Int32
|
||||
pool := newSessionPool(&active)
|
||||
if pool.Pick() != nil {
|
||||
t.Fatal("empty pool must yield nil")
|
||||
}
|
||||
|
||||
ps1 := pool.Add(1, fakeSession(t), nil)
|
||||
ps2 := pool.Add(2, fakeSession(t), nil)
|
||||
if pool.Count() != 2 || active.Load() != 2 {
|
||||
t.Fatalf("count=%d active=%d, want 2/2", pool.Count(), active.Load())
|
||||
}
|
||||
|
||||
seen := map[int]int{}
|
||||
for range 4 {
|
||||
seen[pool.Pick().id]++
|
||||
}
|
||||
if seen[ps1.id] != 2 || seen[ps2.id] != 2 {
|
||||
t.Errorf("round-robin skewed: %v", seen)
|
||||
}
|
||||
|
||||
pool.Remove(ps1)
|
||||
if pool.Count() != 1 || active.Load() != 1 {
|
||||
t.Fatalf("after remove: count=%d active=%d, want 1/1", pool.Count(), active.Load())
|
||||
}
|
||||
for range 3 {
|
||||
if got := pool.Pick(); got != ps2 {
|
||||
t.Fatalf("Pick() = %v, want session 2", got)
|
||||
}
|
||||
}
|
||||
|
||||
pool.Remove(ps2)
|
||||
if pool.Pick() != nil || active.Load() != 0 {
|
||||
t.Errorf("drained pool must yield nil, active=%d", active.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolPickSkipsClosed(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pool := newSessionPool(nil)
|
||||
ps := pool.Add(1, fakeSession(t), nil)
|
||||
_ = ps.sess.Close()
|
||||
if got := pool.Pick(); got != nil {
|
||||
t.Errorf("Pick() = %v, want nil for closed session", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolReadyAndCloseAll(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pool := newSessionPool(nil)
|
||||
select {
|
||||
case <-pool.Ready():
|
||||
t.Fatal("Ready() closed before first session")
|
||||
default:
|
||||
}
|
||||
|
||||
ps := pool.Add(1, fakeSession(t), nil)
|
||||
<-pool.Ready()
|
||||
|
||||
pool.CloseAll()
|
||||
if !ps.sess.IsClosed() {
|
||||
t.Error("CloseAll left session open")
|
||||
}
|
||||
// CloseAll не трогает состав пула: переподнимает сессии maintainSession.
|
||||
if pool.Count() != 1 {
|
||||
t.Errorf("Count() = %d, want 1", pool.Count())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package tcprelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/provider"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/allocpace"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/stats"
|
||||
)
|
||||
|
||||
type fakeAuth struct {
|
||||
authErr error
|
||||
backoffUntil int64
|
||||
handled atomic.Int32
|
||||
reset atomic.Int32
|
||||
dropped atomic.Int32
|
||||
}
|
||||
|
||||
func (a *fakeAuth) IsAuthError(err error) bool {
|
||||
return a.authErr != nil && errors.Is(err, a.authErr)
|
||||
}
|
||||
|
||||
func (a *fakeAuth) HandleAuthError(int) bool {
|
||||
a.handled.Add(1)
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *fakeAuth) ResetErrors(int) { a.reset.Add(1) }
|
||||
func (a *fakeAuth) DropCredentials(int) { a.dropped.Add(1) }
|
||||
|
||||
func (a *fakeAuth) BackoffUntilUnix() int64 { return a.backoffUntil }
|
||||
|
||||
// Фатальная ошибка провайдера обязана останавливать клиента, а не крутиться в ретраях.
|
||||
func TestMaintainSessionReportsFatal(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
auth := &fakeAuth{}
|
||||
deps := &Deps{Log: logx.Nop(), Auth: auth}
|
||||
params := &Params{
|
||||
GetCreds: func(context.Context, int) (string, string, []string, error) {
|
||||
return "", "", nil, provider.ErrFatalNoStreams
|
||||
},
|
||||
}
|
||||
|
||||
fatalCh := make(chan error, 1)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
maintainSession(ctx, deps, params, &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1},
|
||||
1, newSessionPool(nil), allocpace.New(0), func(err error) { fatalCh <- err })
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-fatalCh:
|
||||
if !errors.Is(err, provider.ErrFatalNoStreams) {
|
||||
t.Fatalf("fatal err = %v, want ErrFatalNoStreams", err)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("fatal not reported")
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("maintainSession did not return after fatal")
|
||||
}
|
||||
if auth.reset.Load() != 0 {
|
||||
t.Errorf("ResetErrors called %d times on failure", auth.reset.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// Ошибка авторизации обязана инвалидировать реквизиты, иначе ретраи идут мёртвыми кредами.
|
||||
func TestMaintainSessionHandlesAuthError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
authErr := errors.New("401 Unauthorized")
|
||||
auth := &fakeAuth{authErr: authErr}
|
||||
deps := &Deps{Log: logx.Nop(), Auth: auth}
|
||||
params := &Params{
|
||||
GetCreds: func(context.Context, int) (string, string, []string, error) {
|
||||
return "", "", nil, authErr
|
||||
},
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
maintainSession(ctx, deps, params, &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1},
|
||||
1, newSessionPool(nil), allocpace.New(0), func(error) {})
|
||||
}()
|
||||
|
||||
deadline := time.Now().Add(15 * time.Second)
|
||||
for auth.handled.Load() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if auth.handled.Load() == 0 {
|
||||
t.Fatal("HandleAuthError never called")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(15 * time.Second):
|
||||
t.Fatal("maintainSession did not return after cancel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryDelayHonorsProviderBackoff(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
auth := &fakeAuth{backoffUntil: time.Now().Add(42 * time.Second).Unix()}
|
||||
got := retryDelay(auth, provider.ErrBackoffActive)
|
||||
if got < 30*time.Second || got > 45*time.Second {
|
||||
t.Errorf("retryDelay() = %v, want ~42s from provider lockout", got)
|
||||
}
|
||||
|
||||
stale := &fakeAuth{backoffUntil: time.Now().Add(-time.Minute).Unix()}
|
||||
if got := retryDelay(stale, provider.ErrBackoffActive); got != 5*time.Second {
|
||||
t.Errorf("retryDelay(stale lockout) = %v, want 5s", got)
|
||||
}
|
||||
|
||||
if got := retryDelay(&fakeAuth{}, provider.ErrBackoffActive); got != providerBackoffDelay {
|
||||
t.Errorf("retryDelay(no lockout) = %v, want %v", got, providerBackoffDelay)
|
||||
}
|
||||
}
|
||||
|
||||
// Джиттер разводит одновременный отказ всех сессий пула.
|
||||
func TestRetryDelayJittersOrdinaryErrors(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
seen := map[time.Duration]bool{}
|
||||
for range 64 {
|
||||
d := retryDelay(&fakeAuth{}, errors.New("boom"))
|
||||
if d < setupRetryDelay || d >= setupRetryDelay+setupRetryJitter {
|
||||
t.Fatalf("retryDelay() = %v, want [%v, %v)", d, setupRetryDelay, setupRetryDelay+setupRetryJitter)
|
||||
}
|
||||
seen[d] = true
|
||||
}
|
||||
if len(seen) < 2 {
|
||||
t.Error("retryDelay() constant, jitter missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAwaitDeadOnCancel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
s := &session{smux: fakeSession(t), permDead: make(chan struct{})}
|
||||
go func() { time.Sleep(50 * time.Millisecond); cancel() }()
|
||||
|
||||
if awaitDead(ctx, logx.Nop(), s, 1) {
|
||||
t.Error("awaitDead() = true on ctx cancel, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAwaitDeadOnPermDead(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
permDead := make(chan struct{})
|
||||
s := &session{smux: fakeSession(t), permDead: permDead}
|
||||
close(permDead)
|
||||
|
||||
if !awaitDead(context.Background(), logx.Nop(), s, 1) {
|
||||
t.Error("awaitDead() = false on permDead, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAwaitDeadOnClosedSession(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
sess := fakeSession(t)
|
||||
s := &session{smux: sess, permDead: make(chan struct{})}
|
||||
_ = sess.Close()
|
||||
|
||||
if !awaitDead(context.Background(), logx.Nop(), s, 1) {
|
||||
t.Error("awaitDead() = false on closed smux, want true")
|
||||
}
|
||||
}
|
||||
|
||||
// Рецикл рвёт сессии, но состав пула не трогает: их переподнимает maintainSession.
|
||||
func TestWatchRecycleClosesSessions(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
pool := newSessionPool(nil)
|
||||
ps := pool.Add(1, fakeSession(t), nil)
|
||||
recycle := make(chan struct{}, 1)
|
||||
go watchRecycle(ctx, logx.Nop(), pool, recycle)
|
||||
|
||||
recycle <- struct{}{}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !ps.sess.IsClosed() && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if !ps.sess.IsClosed() {
|
||||
t.Fatal("watchRecycle did not close session")
|
||||
}
|
||||
if pool.Count() != 1 {
|
||||
t.Errorf("Count() = %d, want 1", pool.Count())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextBackoffGrowsAndCaps(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := nextBackoff(0)
|
||||
if d != minAcceptBackoff {
|
||||
t.Fatalf("nextBackoff(0) = %v, want %v", d, minAcceptBackoff)
|
||||
}
|
||||
prev := d
|
||||
for range 20 {
|
||||
d = nextBackoff(d)
|
||||
if d < prev {
|
||||
t.Fatalf("nextBackoff shrank: %v -> %v", prev, d)
|
||||
}
|
||||
prev = d
|
||||
}
|
||||
if d != maxAcceptBackoff {
|
||||
t.Errorf("nextBackoff capped at %v, want %v", d, maxAcceptBackoff)
|
||||
}
|
||||
}
|
||||
|
||||
// Без Auth в Deps пакет обязан работать: тесты и вызовы без провайдера не должны падать.
|
||||
func TestDepsAuthDefaultsToNop(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := &Deps{}
|
||||
if d.auth().IsAuthError(errors.New("x")) {
|
||||
t.Error("nopAuth.IsAuthError() = true")
|
||||
}
|
||||
if d.auth().HandleAuthError(1) {
|
||||
t.Error("nopAuth.HandleAuthError() = true")
|
||||
}
|
||||
if d.auth().BackoffUntilUnix() != 0 {
|
||||
t.Error("nopAuth.BackoffUntilUnix() != 0")
|
||||
}
|
||||
d.auth().ResetErrors(1)
|
||||
d.auth().DropCredentials(1)
|
||||
}
|
||||
|
||||
// Прикладные счётчики не должны включать оверхед ARQ - его считает WireConn.
|
||||
func TestProxyConnCountsApplicationBytes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
backendAddr := echoBackend(t)
|
||||
traffic := stats.New(true)
|
||||
pool := newSessionPool(nil)
|
||||
ps := pool.Add(1, pairedSession(t, ctx, backendAddr), traffic)
|
||||
|
||||
local, remote := net.Pipe()
|
||||
defer func() { _ = local.Close() }()
|
||||
go proxyConn(ctx, logx.Nop(), remote, ps, 1)
|
||||
|
||||
payload := []byte("hello over smux")
|
||||
if _, err := local.Write(payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := make([]byte, len(payload))
|
||||
if err := local.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := local.Read(got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tx, rx := traffic.Counters()
|
||||
if tx != uint64(len(payload)) {
|
||||
t.Errorf("tx = %d, want %d", tx, len(payload))
|
||||
}
|
||||
if rx != uint64(len(payload)) {
|
||||
t.Errorf("rx = %d, want %d", rx, len(payload))
|
||||
}
|
||||
if traffic.LivenessRx() != rx {
|
||||
t.Errorf("LivenessRx() = %d, want %d without WireConn", traffic.LivenessRx(), rx)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
package tcprelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/client/ish"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/clientsdb"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/netconn"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/provider"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/allocpace"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/udprelay"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/randx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/safego"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/stats"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/dtlsdial"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcpmux"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire/shape"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
const (
|
||||
setupRetryDelay = 3 * time.Second
|
||||
setupRetryJitter = 4 * time.Second
|
||||
providerBackoffDelay = 60 * time.Second
|
||||
reconnectDelay = 2 * time.Second
|
||||
sessionPollDelay = time.Second
|
||||
minAcceptBackoff = 5 * time.Millisecond
|
||||
maxAcceptBackoff = time.Second
|
||||
)
|
||||
|
||||
// ErrFatal возвращается при фатальных ошибках провайдера, требующих остановки клиента.
|
||||
var ErrFatal = errors.New("tcprelay: fatal error")
|
||||
|
||||
// GetCredsFunc переиспользуется из udprelay: контракт с провайдером один на оба режима.
|
||||
type GetCredsFunc = udprelay.GetCredsFunc
|
||||
|
||||
// AuthHandler переиспользуется из udprelay: жизненный цикл реквизитов один на оба режима.
|
||||
type AuthHandler = udprelay.AuthHandler
|
||||
|
||||
type Params struct {
|
||||
Host string
|
||||
Port string
|
||||
TransportUDP bool
|
||||
Profile string
|
||||
ObfKey []byte
|
||||
ObfTiming time.Duration
|
||||
GetCreds GetCredsFunc
|
||||
KCPProfile kcpmux.Profile
|
||||
ClientID string
|
||||
TrafficStats *stats.Stats
|
||||
}
|
||||
|
||||
type Deps struct {
|
||||
DTLSDialer *dtlsdial.Dialer
|
||||
Auth AuthHandler
|
||||
Log logx.Logger
|
||||
ConnectedStreams *atomic.Int32
|
||||
OnTURNServer func(ip net.IP)
|
||||
// Recycle рвёт сессии пула; listener переживает рецикл, иначе на каждом
|
||||
// пробуждении рвались бы живые соединения VLESS-клиента.
|
||||
Recycle <-chan struct{}
|
||||
}
|
||||
|
||||
func (d *Deps) log() logx.Logger {
|
||||
if d.Log == nil {
|
||||
return logx.Nop()
|
||||
}
|
||||
return d.Log
|
||||
}
|
||||
|
||||
func (d *Deps) auth() AuthHandler {
|
||||
if d.Auth == nil {
|
||||
return nopAuth{}
|
||||
}
|
||||
return d.Auth
|
||||
}
|
||||
|
||||
type nopAuth struct{}
|
||||
|
||||
func (nopAuth) IsAuthError(error) bool { return false }
|
||||
func (nopAuth) HandleAuthError(int) bool { return false }
|
||||
func (nopAuth) ResetErrors(int) {}
|
||||
func (nopAuth) DropCredentials(int) {}
|
||||
func (nopAuth) BackoffUntilUnix() int64 { return 0 }
|
||||
|
||||
// Run поднимает пул сессий и блокирует вызывающую горутину до отмены ctx.
|
||||
func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, listenAddr string, numSessions int) error {
|
||||
if numSessions <= 0 {
|
||||
numSessions = 1
|
||||
}
|
||||
log := deps.log()
|
||||
pool := newSessionPool(deps.ConnectedStreams)
|
||||
pacer := allocpace.New(allocpace.DefaultInterval)
|
||||
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
// Порт поднимается до первой сессии: иначе Xray получал бы connection refused всё
|
||||
// время перебора реквизитов и решения капчи и успевал пометить outbound мёртвым.
|
||||
listener, err := listen(runCtx, listenAddr, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
stopCloser := context.AfterFunc(runCtx, func() { _ = listener.Close() })
|
||||
defer stopCloser()
|
||||
log.Infof("TCP mode: listening on %s (round-robin across %d sessions)", listenAddr, numSessions)
|
||||
|
||||
fatalCh := make(chan error, 1)
|
||||
fatal := func(err error) {
|
||||
select {
|
||||
case fatalCh <- fmt.Errorf("%w: %w", ErrFatal, err):
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
var wgBG sync.WaitGroup
|
||||
for i := range numSessions {
|
||||
id := i + 1
|
||||
wgBG.Go(func() {
|
||||
_ = safego.Run(log, func() { maintainSession(runCtx, deps, params, peer, id, pool, pacer, fatal) })
|
||||
})
|
||||
}
|
||||
if deps.Recycle != nil {
|
||||
wgBG.Go(func() {
|
||||
_ = safego.Run(log, func() { watchRecycle(runCtx, log, pool, deps.Recycle) })
|
||||
})
|
||||
}
|
||||
wgBG.Go(func() {
|
||||
_ = safego.Run(log, func() { announceReady(runCtx, log, pool, numSessions) })
|
||||
})
|
||||
|
||||
var fatalErr atomic.Pointer[error]
|
||||
watcherDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(watcherDone)
|
||||
select {
|
||||
case ferr := <-fatalCh:
|
||||
fatalErr.Store(&ferr)
|
||||
cancel()
|
||||
case <-runCtx.Done():
|
||||
}
|
||||
}()
|
||||
|
||||
acceptLoop(runCtx, deps, listener, pool)
|
||||
cancel()
|
||||
wgBG.Wait()
|
||||
<-watcherDone
|
||||
if p := fatalErr.Load(); p != nil {
|
||||
return *p
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func announceReady(ctx context.Context, log logx.Logger, pool *sessionPool, numSessions int) {
|
||||
log.Infof("TCP mode: waiting for sessions to connect (total: %d)...", numSessions)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-pool.Ready():
|
||||
log.Infof("TCP mode: pool serving traffic (active: %d)", pool.Count())
|
||||
}
|
||||
}
|
||||
|
||||
func listen(ctx context.Context, addr string, log logx.Logger) (net.Listener, error) {
|
||||
ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tcprelay listen %s: %w", addr, err)
|
||||
}
|
||||
wrapped, err := ish.WrapListener(ln)
|
||||
if err != nil {
|
||||
log.Warnf("tcprelay: failed to wrap listener: %v", err)
|
||||
return ln, nil
|
||||
}
|
||||
return wrapped, nil
|
||||
}
|
||||
|
||||
func watchRecycle(ctx context.Context, log logx.Logger, pool *sessionPool, recycle <-chan struct{}) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-recycle:
|
||||
log.Warnf("TCP mode: recycling %d session(s), listener stays up", pool.Count())
|
||||
pool.CloseAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func acceptLoop(ctx context.Context, deps *Deps, listener net.Listener, pool *sessionPool) {
|
||||
log := deps.log()
|
||||
var wg sync.WaitGroup
|
||||
defer wg.Wait()
|
||||
|
||||
var backoff time.Duration
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
// Отказ обычно устойчив (EMFILE): без паузы цикл сжёг бы ядро на ретраях.
|
||||
backoff = nextBackoff(backoff)
|
||||
log.Errorf("TCP accept error: %s, retry in %s", err, backoff)
|
||||
if !sleep(ctx, backoff) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
backoff = 0
|
||||
|
||||
ps := pool.Pick()
|
||||
if ps == nil {
|
||||
log.Errorf("No active sessions, rejecting connection from %s", conn.RemoteAddr())
|
||||
_ = conn.Close()
|
||||
continue
|
||||
}
|
||||
|
||||
connID := pool.NextConnID()
|
||||
log.Debugf("[session %d] TCP accept #%d from=%s active=%d pool=%d",
|
||||
ps.id, connID, conn.RemoteAddr(), ps.active.Add(1), pool.Count())
|
||||
|
||||
wg.Go(func() {
|
||||
_ = safego.Run(log, func() { proxyConn(ctx, log, conn, ps, connID) })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func nextBackoff(d time.Duration) time.Duration {
|
||||
if d <= 0 {
|
||||
return minAcceptBackoff
|
||||
}
|
||||
if d *= 2; d > maxAcceptBackoff {
|
||||
return maxAcceptBackoff
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func proxyConn(ctx context.Context, log logx.Logger, conn net.Conn, ps *pooledSession, connID uint64) {
|
||||
defer func() { _ = conn.Close() }()
|
||||
defer func() { log.Debugf("[session %d] TCP close #%d active=%d", ps.id, connID, ps.active.Add(-1)) }()
|
||||
|
||||
stream, err := ps.sess.OpenStream()
|
||||
if err != nil {
|
||||
log.Errorf("[session %d] smux open stream for TCP #%d: %s", ps.id, connID, err)
|
||||
return
|
||||
}
|
||||
defer func() { _ = stream.Close() }()
|
||||
|
||||
// Считаем на потоке smux, а не на проводе: пользователю нужны прикладные байты, без
|
||||
// ARQ-оверхеда и ретрансмитов.
|
||||
var counted net.Conn = stream
|
||||
if ps.traffic != nil {
|
||||
counted = &stats.CountingConn{Conn: stream, Stats: ps.traffic}
|
||||
}
|
||||
|
||||
// Ошибки копирования шумят на каждом закрытии соединения - только под -debug.
|
||||
errf := func(format string, v ...any) {
|
||||
if log.DebugEnabled() {
|
||||
log.Debugf(format, v...)
|
||||
}
|
||||
}
|
||||
fromSession, toSession := netconn.BiCopy(ctx, conn, counted, errf)
|
||||
log.Debugf("[session %d] TCP done #%d local<-session=%s local->session=%s",
|
||||
ps.id, connID, stats.FormatByteCount(nonNeg(fromSession)), stats.FormatByteCount(nonNeg(toSession)))
|
||||
}
|
||||
|
||||
// session - живой стек одной сессии; permDead закрывается при смерти TURN channel-bind.
|
||||
type session struct {
|
||||
smux *smux.Session
|
||||
permDead <-chan struct{}
|
||||
cleanup func()
|
||||
}
|
||||
|
||||
func maintainSession(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, id int, pool *sessionPool, pacer *allocpace.Pacer, fatal func(error)) {
|
||||
log := deps.log()
|
||||
auth := deps.auth()
|
||||
for ctx.Err() == nil {
|
||||
s, err := createSession(ctx, deps, params, peer, id, pacer)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if errors.Is(err, provider.ErrFatalNoStreams) {
|
||||
log.Errorf("[session %d] Fatal provider error. Shutting down application.", id)
|
||||
fatal(err)
|
||||
return
|
||||
}
|
||||
if auth.IsAuthError(err) {
|
||||
auth.HandleAuthError(id)
|
||||
}
|
||||
d := retryDelay(auth, err)
|
||||
log.Errorf("[session %d] setup error: %s, retry in %s", id, err, d.Truncate(time.Millisecond))
|
||||
if !sleep(ctx, d) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
auth.ResetErrors(id)
|
||||
|
||||
ps := pool.Add(id, s.smux, params.TrafficStats)
|
||||
log.Infof("[session %d] connected (active: %d)", id, pool.Count())
|
||||
|
||||
dead := awaitDead(ctx, log, s, id)
|
||||
pool.Remove(ps)
|
||||
s.cleanup()
|
||||
if !dead {
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[session %d] disconnected (active: %d), reconnecting...", id, pool.Count())
|
||||
if !sleep(ctx, reconnectDelay) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// retryDelay: пауза провайдера важнее собственной - ретрай в её середине только продлевает
|
||||
// локаут и жжёт персону. Джиттер разводит одновременный отказ всех сессий пула.
|
||||
func retryDelay(auth AuthHandler, err error) time.Duration {
|
||||
if errors.Is(err, provider.ErrBackoffActive) {
|
||||
if until := auth.BackoffUntilUnix(); until > 0 {
|
||||
if d := time.Until(time.Unix(until, 0)); d > 0 {
|
||||
return d
|
||||
}
|
||||
return 5 * time.Second
|
||||
}
|
||||
return providerBackoffDelay
|
||||
}
|
||||
|
||||
return setupRetryDelay + time.Duration(randx.Intn(int(setupRetryJitter/time.Millisecond)))*time.Millisecond
|
||||
}
|
||||
|
||||
// awaitDead: false - вышли по отмене ctx, а не по смерти сессии.
|
||||
func awaitDead(ctx context.Context, log logx.Logger, s *session, id int) bool {
|
||||
t := time.NewTicker(sessionPollDelay)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-s.permDead:
|
||||
log.Warnf("[session %d] TURN channel-bind умер - рецикл allocation", id)
|
||||
return true
|
||||
case <-t.C:
|
||||
if s.smux.IsClosed() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// createSession поднимает стек TURN -> obf -> DTLS -> KCP -> smux.
|
||||
func createSession(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, id int, pacer *allocpace.Pacer) (*session, error) {
|
||||
log := deps.log()
|
||||
var closers []func()
|
||||
cleanup := func() {
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
closers[i]()
|
||||
}
|
||||
}
|
||||
|
||||
if !pacer.Wait(ctx) {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
stream, err := udprelay.DialTURN(ctx, params.Host, params.Port, params.TransportUDP, peer, id, params.GetCreds, log)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
relayedAddr := stream.Relay.LocalAddr().String()
|
||||
closers = append(closers, func() {
|
||||
// Недошедший deallocate держит квоту VK до конца её lifetime, и следующий
|
||||
// Allocate по тем же кредам ловит 486 - такие креды переиспользовать нельзя.
|
||||
cerr := stream.Close()
|
||||
log.Infof("[session %d] TURN allocation released: relayed=%s deallocate=%v", id, relayedAddr, cerr)
|
||||
if cerr != nil {
|
||||
deps.auth().DropCredentials(id)
|
||||
}
|
||||
})
|
||||
if deps.OnTURNServer != nil {
|
||||
deps.OnTURNServer(stream.ServerUDPAddr.IP)
|
||||
}
|
||||
log.Debugf("[session %d] relayed-address=%s", id, relayedAddr)
|
||||
|
||||
codec, err := wire.NewClientCodec(params.Profile, params.ObfKey)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, fmt.Errorf("obf init: %w", err)
|
||||
}
|
||||
relayConn := stream.Relay
|
||||
if params.ObfTiming > 0 {
|
||||
relayConn = shape.WrapPacketConn(relayConn, params.ObfTiming)
|
||||
log.Debugf("[session %d] obf-timing=%s", id, params.ObfTiming)
|
||||
}
|
||||
dtlsConn, err := deps.DTLSDialer.Dial(ctx, &wire.RelayPacketConn{Relay: relayConn, Peer: peer, Codec: codec}, peer)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, fmt.Errorf("DTLS handshake: %w", err)
|
||||
}
|
||||
closers = append(closers, func() { _ = dtlsConn.Close() })
|
||||
|
||||
// Wire-контракт: Client ID первой app-record, до KCP.
|
||||
if err = clientsdb.WriteClientID(dtlsConn, params.ClientID, clientsdb.ModeTCP); err != nil {
|
||||
cleanup()
|
||||
return nil, fmt.Errorf("send client ID: %w", err)
|
||||
}
|
||||
|
||||
var counted net.Conn = dtlsConn
|
||||
if params.TrafficStats != nil {
|
||||
counted = &stats.WireConn{Conn: counted, Stats: params.TrafficStats}
|
||||
}
|
||||
kcpSess, err := kcpmux.Dial(counted, params.KCPProfile)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, err
|
||||
}
|
||||
closers = append(closers, func() { _ = kcpSess.Close() })
|
||||
|
||||
smuxSess, err := smux.Client(kcpSess, kcpmux.SmuxConfig())
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, fmt.Errorf("smux client: %w", err)
|
||||
}
|
||||
closers = append(closers, func() { _ = smuxSess.Close() })
|
||||
log.Debugf("[session %d] smux session established", id)
|
||||
|
||||
return &session{smux: smuxSess, permDead: stream.PermDead, cleanup: cleanup}, nil
|
||||
}
|
||||
|
||||
func sleep(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-t.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func nonNeg(n int64) uint64 {
|
||||
if n < 0 {
|
||||
return 0
|
||||
}
|
||||
return uint64(n)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Package tcpserver - серверная сторона tcp-режима: KCP+smux поверх DTLS, каждый
|
||||
// smux-поток форвардится в локальный TCP backend.
|
||||
package tcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/netconn"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcpmux"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
const backendDialTimeout = 10 * time.Second
|
||||
|
||||
// Handle блокирует вызывающую горутину до закрытия сессии клиентом или ctx.
|
||||
func Handle(ctx context.Context, logger logx.Logger, dtlsConn net.Conn, connectAddr string, profile kcpmux.Profile) {
|
||||
kcpSess, err := kcpmux.Accept(dtlsConn, profile)
|
||||
if err != nil {
|
||||
logger.Errorf("tcpserver: %s", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := kcpSess.Close(); closeErr != nil {
|
||||
logger.Warnf("tcpserver: close KCP session: %v", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
smuxSess, err := smux.Server(kcpSess, kcpmux.SmuxConfig())
|
||||
if err != nil {
|
||||
logger.Errorf("tcpserver: smux server: %s", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := smuxSess.Close(); closeErr != nil {
|
||||
logger.Warnf("tcpserver: close smux session: %v", closeErr)
|
||||
}
|
||||
}()
|
||||
logger.Debugf("tcpserver: smux session established")
|
||||
|
||||
// ctx живёт всё время процесса - без stop() хук копился бы на каждую сессию.
|
||||
stopOnCancel := context.AfterFunc(ctx, func() { _ = smuxSess.Close() })
|
||||
defer stopOnCancel()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for {
|
||||
stream, err := smuxSess.AcceptStream()
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
logger.Debugf("tcpserver: smux accept: %s", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
wg.Go(func() { handleStream(ctx, logger, stream, connectAddr) })
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func handleStream(ctx context.Context, logger logx.Logger, s *smux.Stream, connectAddr string) {
|
||||
defer func() {
|
||||
if err := s.Close(); err != nil && err != smux.ErrGoAway {
|
||||
logger.Warnf("tcpserver: close smux stream: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
backend, err := (&net.Dialer{Timeout: backendDialTimeout}).DialContext(ctx, "tcp", connectAddr)
|
||||
if err != nil {
|
||||
logger.Errorf("tcpserver: backend dial %s: %s", connectAddr, err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := backend.Close(); closeErr != nil {
|
||||
logger.Warnf("tcpserver: close backend connection: %v", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
netconn.BiCopy(ctx, s, backend, logger.Debugf)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package tcpserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/netconn"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcpmux"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// echoBackend отвечает тем же, что получил, - роль локального Xray на сервере.
|
||||
func echoBackend(t *testing.T) string {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0") //nolint:noctx // тестовый сокет
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
|
||||
go func() {
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer func() { _ = conn.Close() }()
|
||||
_, _ = io.Copy(conn, conn)
|
||||
}()
|
||||
}
|
||||
}()
|
||||
return ln.Addr().String()
|
||||
}
|
||||
|
||||
func TestHandleForwardsStreamToBackend(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
backendAddr := echoBackend(t)
|
||||
clientConn, serverConn := netconn.DatagramPipe(2048, 1024)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
Handle(ctx, logx.Nop(), serverConn, backendAddr, kcpmux.DefaultProfile())
|
||||
}()
|
||||
|
||||
kcpSess, err := kcpmux.Dial(clientConn, kcpmux.DefaultProfile())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
smuxSess, err := smux.Client(kcpSess, kcpmux.SmuxConfig())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for i := range 2 {
|
||||
stream, serr := smuxSess.OpenStream()
|
||||
if serr != nil {
|
||||
t.Fatalf("stream %d: %v", i, serr)
|
||||
}
|
||||
payload := bytes.Repeat([]byte{byte('a' + i)}, 64*1024)
|
||||
go func() { _, _ = stream.Write(payload) }()
|
||||
|
||||
got := make([]byte, len(payload))
|
||||
if derr := stream.SetReadDeadline(time.Now().Add(30 * time.Second)); derr != nil {
|
||||
t.Fatal(derr)
|
||||
}
|
||||
if _, rerr := io.ReadFull(stream, got); rerr != nil {
|
||||
t.Fatalf("stream %d read: %v", i, rerr)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatalf("stream %d: echo mismatch", i)
|
||||
}
|
||||
_ = stream.Close()
|
||||
}
|
||||
|
||||
_ = smuxSess.Close()
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("Handle did not return after cancel")
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ func TURNLoop(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case pair := <-connchan:
|
||||
if !deps.allocPace.wait(ctx) {
|
||||
if !deps.allocPace.Wait(ctx) {
|
||||
return
|
||||
}
|
||||
c := make(chan error, 1)
|
||||
@@ -158,7 +158,7 @@ func dtlsSession(dtlsctx context.Context, dtlscancel context.CancelFunc, deps *D
|
||||
}()
|
||||
deps.log().Debugf("[STREAM %d] Established DTLS connection", streamID)
|
||||
|
||||
if err := clientsdb.WriteClientID(dtlsConn, params.ClientID); err != nil {
|
||||
if err := clientsdb.WriteClientID(dtlsConn, params.ClientID, clientsdb.ModeUDP); err != nil {
|
||||
return fmt.Errorf("failed to write client ID: %w", err)
|
||||
}
|
||||
if okchan != nil {
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
package udprelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Квота TURN считается на username, поэтому залп Allocate от всех стримов сразу упирается
|
||||
// в неё плотнее, чем очередь: шлюз раздаёт слоты по одному на allocPaceInterval.
|
||||
const allocPaceInterval = 200 * time.Millisecond
|
||||
|
||||
type allocPacer struct {
|
||||
mu sync.Mutex
|
||||
next time.Time
|
||||
step time.Duration
|
||||
}
|
||||
|
||||
func newAllocPacer(step time.Duration) *allocPacer {
|
||||
return &allocPacer{step: step}
|
||||
}
|
||||
|
||||
// wait возвращает false, только если ctx отменён - слот всё равно занят и не переиспользуется.
|
||||
func (p *allocPacer) wait(ctx context.Context) bool {
|
||||
if p == nil {
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
wait := time.Until(p.slot())
|
||||
if wait <= 0 {
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
t := time.NewTimer(wait)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (p *allocPacer) slot() time.Time {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
now := time.Now()
|
||||
if p.next.Before(now) {
|
||||
p.next = now
|
||||
}
|
||||
slot := p.next
|
||||
p.next = slot.Add(p.step)
|
||||
return slot
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/allocpace"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/safego"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/stats"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/dtlsdial"
|
||||
@@ -51,7 +52,7 @@ type Deps struct {
|
||||
ConnectedStreams *atomic.Int32
|
||||
OnTURNServer func(ip net.IP)
|
||||
fatalCh chan error
|
||||
allocPace *allocPacer
|
||||
allocPace *allocpace.Pacer
|
||||
}
|
||||
|
||||
func (d *Deps) log() logx.Logger {
|
||||
@@ -92,7 +93,7 @@ func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, log
|
||||
ConnectedStreams: connectedStreams,
|
||||
OnTURNServer: onTURNServer,
|
||||
fatalCh: fatalCh,
|
||||
allocPace: newAllocPacer(allocPaceInterval),
|
||||
allocPace: allocpace.New(allocpace.DefaultInterval),
|
||||
}
|
||||
|
||||
runCtx, runCancel := context.WithCancel(ctx)
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/provider"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/provider/vk"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/tcprelay"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/udprelay"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/routemgr"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/safego"
|
||||
@@ -43,6 +44,7 @@ var (
|
||||
const (
|
||||
defaultStatusInterval = 500 * time.Millisecond
|
||||
defaultUDPHandshakeTimeout = 20 * time.Second
|
||||
defaultTCPHandshakeTimeout = 30 * time.Second
|
||||
defaultHandshakeConcurrency = 3
|
||||
|
||||
// Порог вдвое больше тика: сон короче порога всё равно пропускаем, а тик почаще
|
||||
@@ -60,6 +62,7 @@ type Options struct {
|
||||
|
||||
StatusInterval time.Duration
|
||||
UDPHandshakeTimeout time.Duration
|
||||
TCPHandshakeTimeout time.Duration
|
||||
HandshakeConcurrency int
|
||||
// WakeProbeWindow - окно проверки живости канала после пробуждения.
|
||||
WakeProbeWindow time.Duration
|
||||
@@ -74,6 +77,9 @@ func (o Options) withDefaults() Options {
|
||||
if o.UDPHandshakeTimeout <= 0 {
|
||||
o.UDPHandshakeTimeout = defaultUDPHandshakeTimeout
|
||||
}
|
||||
if o.TCPHandshakeTimeout <= 0 {
|
||||
o.TCPHandshakeTimeout = defaultTCPHandshakeTimeout
|
||||
}
|
||||
if o.HandshakeConcurrency <= 0 {
|
||||
o.HandshakeConcurrency = defaultHandshakeConcurrency
|
||||
}
|
||||
@@ -124,6 +130,7 @@ type Session struct {
|
||||
status atomic.Pointer[statusInfo]
|
||||
started atomic.Bool
|
||||
reconnectCh chan struct{}
|
||||
recycleCh chan struct{}
|
||||
wakeCh chan struct{}
|
||||
}
|
||||
|
||||
@@ -143,6 +150,7 @@ func New(cfg *config.Client, deps Deps) (*Session, error) {
|
||||
opts: deps.Options.withDefaults(),
|
||||
total: total,
|
||||
reconnectCh: make(chan struct{}, 1),
|
||||
recycleCh: make(chan struct{}, 1),
|
||||
wakeCh: make(chan struct{}, 1),
|
||||
}
|
||||
if s.opts.Traffic {
|
||||
@@ -269,8 +277,12 @@ func (s *Session) Wake() {
|
||||
}
|
||||
|
||||
func (s *Session) Reconnect() {
|
||||
ch := s.reconnectCh
|
||||
if s.cfg.Proxy.Mode == config.ProxyModeTCP {
|
||||
ch = s.recycleCh
|
||||
}
|
||||
select {
|
||||
case s.reconnectCh <- struct{}{}:
|
||||
case ch <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -299,7 +311,7 @@ func (s *Session) wakeNeedsRecycle(ctx context.Context) bool {
|
||||
if s.traffic == nil {
|
||||
return true
|
||||
}
|
||||
_, before := s.traffic.stats.Counters()
|
||||
before := s.traffic.stats.LivenessRx()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
@@ -310,7 +322,7 @@ func (s *Session) wakeNeedsRecycle(ctx context.Context) bool {
|
||||
case <-s.wakeCh:
|
||||
default:
|
||||
}
|
||||
_, after := s.traffic.stats.Counters()
|
||||
after := s.traffic.stats.LivenessRx()
|
||||
if after > before {
|
||||
log.Warnf("wake: канал жив (+%d B за %s) - рецикл не нужен", after-before, s.opts.WakeProbeWindow)
|
||||
return false
|
||||
@@ -391,13 +403,13 @@ func (s *Session) watch(ctx context.Context, cancel context.CancelFunc) error {
|
||||
|
||||
func (s *Session) relay(ctx context.Context, prov provider.Provider, peer *net.UDPAddr) error {
|
||||
log := s.deps.Logger
|
||||
getCreds := func(ctx context.Context, streamID int) (string, string, []string, error) {
|
||||
getCreds := udprelay.GetCredsFunc(func(ctx context.Context, streamID int) (string, string, []string, error) {
|
||||
c, err := prov.GetCredentials(ctx, streamID)
|
||||
if err != nil {
|
||||
return "", "", nil, err
|
||||
}
|
||||
return c.User, c.Pass, c.ServerAddrs, nil
|
||||
}
|
||||
})
|
||||
|
||||
// host-route для IP TURN-серверов в обход VPN-туннеля.
|
||||
var routeCallback func(net.IP)
|
||||
@@ -414,6 +426,14 @@ func (s *Session) relay(ctx context.Context, prov provider.Provider, peer *net.U
|
||||
}
|
||||
}
|
||||
|
||||
if s.cfg.Proxy.Mode == config.ProxyModeTCP {
|
||||
return s.relayTCP(ctx, prov, getCreds, peer, routeCallback)
|
||||
}
|
||||
return s.relayUDP(ctx, prov, getCreds, peer, routeCallback)
|
||||
}
|
||||
|
||||
func (s *Session) relayUDP(ctx context.Context, prov provider.Provider, getCreds udprelay.GetCredsFunc, peer *net.UDPAddr, routeCallback func(net.IP)) error {
|
||||
log := s.deps.Logger
|
||||
local, err := s.localConn(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -433,13 +453,40 @@ func (s *Session) relay(ctx context.Context, prov provider.Provider, peer *net.U
|
||||
Profile: string(s.cfg.Obf.Profile),
|
||||
ObfKey: s.cfg.Obf.Key,
|
||||
ObfTiming: s.cfg.Obf.Timing,
|
||||
GetCreds: udprelay.GetCredsFunc(getCreds),
|
||||
GetCreds: getCreds,
|
||||
ClientID: s.cfg.ClientID,
|
||||
TrafficStats: s.trafficStats(),
|
||||
}
|
||||
return udprelay.Run(ctx, dialer, prov, log, &s.connected, routeCallback, params, peer, local, s.total)
|
||||
}
|
||||
|
||||
func (s *Session) relayTCP(ctx context.Context, prov provider.Provider, getCreds udprelay.GetCredsFunc, peer *net.UDPAddr, routeCallback func(net.IP)) error {
|
||||
deps := &tcprelay.Deps{
|
||||
DTLSDialer: &dtlsdial.Dialer{
|
||||
HandshakeTimeout: s.opts.TCPHandshakeTimeout,
|
||||
HandshakeSem: make(chan struct{}, s.opts.HandshakeConcurrency),
|
||||
},
|
||||
Auth: prov,
|
||||
Log: s.deps.Logger,
|
||||
ConnectedStreams: &s.connected,
|
||||
OnTURNServer: routeCallback,
|
||||
Recycle: s.recycleCh,
|
||||
}
|
||||
params := &tcprelay.Params{
|
||||
Host: s.cfg.TURN.Host,
|
||||
Port: s.cfg.TURN.Port,
|
||||
TransportUDP: s.cfg.TURN.TransportUDP,
|
||||
Profile: string(s.cfg.Obf.Profile),
|
||||
ObfKey: s.cfg.Obf.Key,
|
||||
ObfTiming: s.cfg.Obf.Timing,
|
||||
GetCreds: getCreds,
|
||||
KCPProfile: s.cfg.KCP.Profile,
|
||||
ClientID: s.cfg.ClientID,
|
||||
TrafficStats: s.trafficStats(),
|
||||
}
|
||||
return tcprelay.Run(ctx, deps, params, peer, s.cfg.Proxy.Listen, s.total)
|
||||
}
|
||||
|
||||
func (s *Session) localConn(ctx context.Context) (net.PacketConn, error) {
|
||||
if s.deps.LocalPipe != nil {
|
||||
s.deps.Logger.Infof("local peer: in-process pipe (no loopback socket)")
|
||||
|
||||
@@ -325,3 +325,35 @@ func TestRelayLoopTurnsPanicIntoError(t *testing.T) {
|
||||
t.Fatal("relayLoop() hung on panic")
|
||||
}
|
||||
}
|
||||
|
||||
// В tcp-режиме рецикл идёт в пул, а не в отмену попытки: отмена закрыла бы listener.
|
||||
func TestReconnectRoutesByMode(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tcp, err := New(&config.Client{Proxy: config.ProxyOpts{Mode: config.ProxyModeTCP}}, Deps{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tcp.Reconnect()
|
||||
select {
|
||||
case <-tcp.recycleCh:
|
||||
default:
|
||||
t.Error("tcp mode: recycleCh empty")
|
||||
}
|
||||
select {
|
||||
case <-tcp.reconnectCh:
|
||||
t.Error("tcp mode: reconnectCh must stay empty")
|
||||
default:
|
||||
}
|
||||
|
||||
udp, err := New(&config.Client{Proxy: config.ProxyOpts{Mode: config.ProxyModeUDP}}, Deps{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
udp.Reconnect()
|
||||
select {
|
||||
case <-udp.reconnectCh:
|
||||
default:
|
||||
t.Error("udp mode: reconnectCh empty")
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package stats
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
type Stats struct {
|
||||
tx atomic.Uint64
|
||||
rx atomic.Uint64
|
||||
wireRx atomic.Uint64
|
||||
enabled bool
|
||||
}
|
||||
|
||||
@@ -22,6 +24,19 @@ func (s *Stats) Counters() (tx, rx uint64) {
|
||||
return s.tx.Load(), s.rx.Load()
|
||||
}
|
||||
|
||||
// LivenessRx - приём на проводе: служебные кадры транспорта тоже подтверждают живость
|
||||
// канала, а прикладной счётчик на простое стоит.
|
||||
func (s *Stats) LivenessRx() uint64 {
|
||||
return s.rx.Load() + s.wireRx.Load()
|
||||
}
|
||||
|
||||
func (s *Stats) AddWireRx(n int) {
|
||||
if n <= 0 || !s.enabled {
|
||||
return
|
||||
}
|
||||
s.wireRx.Add(uint64(n))
|
||||
}
|
||||
|
||||
func (s *Stats) AddTx(n int) {
|
||||
if n <= 0 {
|
||||
return
|
||||
@@ -57,3 +72,45 @@ func FormatBitsPerSecond(bytes uint64, interval time.Duration) string {
|
||||
}
|
||||
return fmt.Sprintf("%.0f bit/s", bps)
|
||||
}
|
||||
|
||||
// FormatByteCount форматирует количество байт в человекочитаемый вид (B, KiB, MiB).
|
||||
func FormatByteCount(bytes uint64) string {
|
||||
if bytes >= 1024*1024 {
|
||||
return fmt.Sprintf("%.2f MiB", float64(bytes)/(1024*1024))
|
||||
}
|
||||
if bytes >= 1024 {
|
||||
return fmt.Sprintf("%.1f KiB", float64(bytes)/1024)
|
||||
}
|
||||
return fmt.Sprintf("%d B", bytes)
|
||||
}
|
||||
|
||||
// CountingConn учитывает прикладные байты - те, что видит пользователь в UI.
|
||||
type CountingConn struct {
|
||||
net.Conn
|
||||
Stats *Stats
|
||||
}
|
||||
|
||||
func (c *CountingConn) Read(p []byte) (int, error) {
|
||||
n, err := c.Conn.Read(p)
|
||||
c.Stats.AddRx(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (c *CountingConn) Write(p []byte) (int, error) {
|
||||
n, err := c.Conn.Write(p)
|
||||
c.Stats.AddTx(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// WireConn учитывает байты на проводе (с оверхедом транспорта и ретрансмитами) - только
|
||||
// для проверки живости, в пользовательские счётчики они не идут.
|
||||
type WireConn struct {
|
||||
net.Conn
|
||||
Stats *Stats
|
||||
}
|
||||
|
||||
func (c *WireConn) Read(p []byte) (int, error) {
|
||||
n, err := c.Conn.Read(p)
|
||||
c.Stats.AddWireRx(n)
|
||||
return n, err
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package stats
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -67,3 +69,81 @@ func TestStatsEnabledAccumulates(t *testing.T) {
|
||||
t.Fatalf("Counters() = (%d, %d), want (150, 7)", tx, rx)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatByteCount(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []struct {
|
||||
bytes uint64
|
||||
want string
|
||||
}{
|
||||
{0, "0 B"},
|
||||
{1023, "1023 B"},
|
||||
{1024, "1.0 KiB"},
|
||||
{1024 * 1024, "1.00 MiB"},
|
||||
{2 * 1024 * 1024, "2.00 MiB"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := FormatByteCount(c.bytes)
|
||||
if got != c.want {
|
||||
t.Errorf("FormatByteCount(%d) = %q, want %q", c.bytes, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCountingConnCounts(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
c1, c2 := net.Pipe()
|
||||
defer func() { _ = c1.Close() }()
|
||||
defer func() { _ = c2.Close() }()
|
||||
|
||||
st := New(true)
|
||||
conn := &CountingConn{Conn: c1, Stats: st}
|
||||
|
||||
go func() {
|
||||
peer := make([]byte, 4)
|
||||
_, _ = io.ReadFull(c2, peer)
|
||||
_, _ = c2.Write([]byte("pong"))
|
||||
}()
|
||||
|
||||
if _, err := conn.Write([]byte("ping")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
buf := make([]byte, 4)
|
||||
if _, err := io.ReadFull(conn, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tx, rx := st.Counters()
|
||||
if tx != 4 || rx != 4 {
|
||||
t.Errorf("tx=%d rx=%d, want 4/4", tx, rx)
|
||||
}
|
||||
}
|
||||
|
||||
// Живость канала подтверждают и служебные кадры транспорта, а UI они врали бы.
|
||||
func TestLivenessRxSeparateFromUserCounters(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := New(true)
|
||||
s.AddRx(100)
|
||||
s.AddTx(50)
|
||||
s.AddWireRx(900)
|
||||
|
||||
tx, rx := s.Counters()
|
||||
if tx != 50 || rx != 100 {
|
||||
t.Errorf("Counters() = %d/%d, want 50/100", tx, rx)
|
||||
}
|
||||
if got := s.LivenessRx(); got != 1000 {
|
||||
t.Errorf("LivenessRx() = %d, want 1000", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddWireRxRespectsDisabled(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
s := New(false)
|
||||
s.AddWireRx(512)
|
||||
if got := s.LivenessRx(); got != 0 {
|
||||
t.Errorf("LivenessRx() = %d, want 0 when disabled", got)
|
||||
}
|
||||
}
|
||||
@@ -62,3 +62,19 @@ func TestParse(t *testing.T) {
|
||||
t.Errorf("Node[1].URI.Peer = %v, want 2.2.2.2:56000", n2.URI.Peer)
|
||||
}
|
||||
}
|
||||
|
||||
// Подписка наследует поля uri: mode должен доезжать до клиента без потерь.
|
||||
func TestParseCarriesMode(t *testing.T) {
|
||||
link := (&uri.Config{Version: 1, Provider: "vk", Peer: "1.1.1.1:56000", Mode: "tcp"}).String()
|
||||
|
||||
s, err := Parse(strings.NewReader(link + "\n"))
|
||||
if err != nil {
|
||||
t.Fatalf("Parse error: %v", err)
|
||||
}
|
||||
if len(s.Nodes) != 1 {
|
||||
t.Fatalf("Nodes = %d, want 1", len(s.Nodes))
|
||||
}
|
||||
if s.Nodes[0].URI.Mode != "tcp" {
|
||||
t.Errorf("Mode = %q, want tcp", s.Nodes[0].URI.Mode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// Package kcpmux собирает надёжный мультиплексированный транспорт поверх датаграммного
|
||||
// канала: KCP (ARQ) -> smux (потоки). Нужен, потому что relayed-данные TURN всегда
|
||||
// датаграммы, даже при -transport tcp, и TCP-поток по ним без ARQ не построить.
|
||||
package kcpmux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/xtaci/kcp-go/v5"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// acceptTimeout ограничивает ожидание первой KCP-датаграммы от клиента на сервере.
|
||||
const acceptTimeout = 30 * time.Second
|
||||
|
||||
// Profile - параметры конгестии KCP; должен совпадать по смыслу с флагами -kcp-*.
|
||||
type Profile struct {
|
||||
NoDelay int
|
||||
Interval int
|
||||
Resend int
|
||||
NC int
|
||||
SndWnd int
|
||||
RcvWnd int
|
||||
MTU int
|
||||
ACKNoDelay bool
|
||||
}
|
||||
|
||||
func DefaultProfile() Profile {
|
||||
return Profile{
|
||||
NoDelay: 1,
|
||||
Interval: 20,
|
||||
Resend: 2,
|
||||
NC: 1,
|
||||
SndWnd: 512,
|
||||
RcvWnd: 512,
|
||||
MTU: 1200,
|
||||
ACKNoDelay: true,
|
||||
}
|
||||
}
|
||||
|
||||
// PacketConn адаптирует потоко-ориентированный net.Conn (DTLS) к net.PacketConn для KCP:
|
||||
// DTLS сохраняет границы записей, поэтому Read/Write отображаются в датаграммы один в один.
|
||||
type PacketConn struct {
|
||||
conn net.Conn
|
||||
}
|
||||
|
||||
func NewPacketConn(conn net.Conn) *PacketConn { return &PacketConn{conn: conn} }
|
||||
|
||||
func (d *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
n, err := d.conn.Read(b)
|
||||
return n, d.conn.RemoteAddr(), err
|
||||
}
|
||||
|
||||
func (d *PacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
||||
return d.conn.Write(b)
|
||||
}
|
||||
|
||||
func (d *PacketConn) Close() error { return d.conn.Close() }
|
||||
func (d *PacketConn) LocalAddr() net.Addr { return d.conn.LocalAddr() }
|
||||
func (d *PacketConn) SetDeadline(t time.Time) error { return d.conn.SetDeadline(t) }
|
||||
func (d *PacketConn) SetReadDeadline(t time.Time) error { return d.conn.SetReadDeadline(t) }
|
||||
func (d *PacketConn) SetWriteDeadline(t time.Time) error { return d.conn.SetWriteDeadline(t) }
|
||||
|
||||
// Dial поднимает клиентскую KCP-сессию поверх датаграммного conn.
|
||||
func Dial(conn net.Conn, profile Profile) (*kcp.UDPSession, error) {
|
||||
block, err := noneCrypt()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sess, err := kcp.NewConn2(conn.RemoteAddr(), block, 0, 0, NewPacketConn(conn))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("kcpmux dial: %w", err)
|
||||
}
|
||||
apply(sess, profile)
|
||||
return sess, nil
|
||||
}
|
||||
|
||||
// ServerSession - принятая сессия вместе с породившим её листенером: листенер держит
|
||||
// демультиплексор поверх conn, и без его закрытия он пережил бы сессию.
|
||||
type ServerSession struct {
|
||||
*kcp.UDPSession
|
||||
listener *kcp.Listener
|
||||
}
|
||||
|
||||
func (s *ServerSession) Close() error {
|
||||
err := s.UDPSession.Close()
|
||||
if lerr := s.listener.Close(); err == nil {
|
||||
err = lerr
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Accept ждёт первую KCP-датаграмму на conn и возвращает серверную сессию.
|
||||
func Accept(conn net.Conn, profile Profile) (*ServerSession, error) {
|
||||
block, err := noneCrypt()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
listener, err := kcp.ServeConn(block, 0, 0, NewPacketConn(conn))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("kcpmux serve: %w", err)
|
||||
}
|
||||
if err = listener.SetDeadline(time.Now().Add(acceptTimeout)); err != nil {
|
||||
_ = listener.Close()
|
||||
return nil, fmt.Errorf("kcpmux accept deadline: %w", err)
|
||||
}
|
||||
sess, err := listener.AcceptKCP()
|
||||
if err != nil {
|
||||
_ = listener.Close()
|
||||
return nil, fmt.Errorf("kcpmux accept: %w", err)
|
||||
}
|
||||
apply(sess, profile)
|
||||
return &ServerSession{UDPSession: sess, listener: listener}, nil
|
||||
}
|
||||
|
||||
// SmuxConfig - параметры smux, общие для клиента и сервера (буферы должны совпадать).
|
||||
func SmuxConfig() *smux.Config {
|
||||
cfg := smux.DefaultConfig()
|
||||
cfg.MaxReceiveBuffer = 4 * 1024 * 1024
|
||||
cfg.MaxStreamBuffer = 1 * 1024 * 1024
|
||||
cfg.KeepAliveInterval = 10 * time.Second
|
||||
cfg.KeepAliveTimeout = 30 * time.Second
|
||||
return cfg
|
||||
}
|
||||
|
||||
// noneCrypt - шифрование не нужно, канал уже под DTLS.
|
||||
func noneCrypt() (kcp.BlockCrypt, error) {
|
||||
block, err := kcp.NewNoneBlockCrypt(nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("kcpmux crypt: %w", err)
|
||||
}
|
||||
return block, nil
|
||||
}
|
||||
|
||||
func apply(sess *kcp.UDPSession, p Profile) {
|
||||
sess.SetNoDelay(p.NoDelay, p.Interval, p.Resend, p.NC)
|
||||
sess.SetWindowSize(p.SndWnd, p.RcvWnd)
|
||||
sess.SetMtu(p.MTU)
|
||||
sess.SetACKNoDelay(p.ACKNoDelay)
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package kcpmux
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"io"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/netconn"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// datagramConn подаёт пары PacketPipe как net.Conn с сохранением границ датаграмм;
|
||||
// dropEvery роняет каждую N-ю отправку, чтобы проверить ARQ.
|
||||
type datagramConn struct {
|
||||
net.PacketConn
|
||||
remote net.Addr
|
||||
dropEvery uint64
|
||||
sent atomic.Uint64
|
||||
}
|
||||
|
||||
func (c *datagramConn) Read(b []byte) (int, error) {
|
||||
n, _, err := c.ReadFrom(b)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (c *datagramConn) Write(b []byte) (int, error) {
|
||||
if c.dropEvery > 0 && c.sent.Add(1)%c.dropEvery == 0 {
|
||||
return len(b), nil
|
||||
}
|
||||
return c.WriteTo(b, c.remote)
|
||||
}
|
||||
|
||||
func (c *datagramConn) RemoteAddr() net.Addr { return c.remote }
|
||||
|
||||
func pipePair(dropEvery uint64) (*datagramConn, *datagramConn) {
|
||||
a, b := netconn.PacketPipe(2048, 1024)
|
||||
return &datagramConn{PacketConn: a, remote: b.LocalAddr(), dropEvery: dropEvery},
|
||||
&datagramConn{PacketConn: b, remote: a.LocalAddr()}
|
||||
}
|
||||
|
||||
func TestRoundTrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
runRoundTrip(t, 0)
|
||||
}
|
||||
|
||||
func TestRoundTripWithLoss(t *testing.T) {
|
||||
t.Parallel()
|
||||
runRoundTrip(t, 7)
|
||||
}
|
||||
|
||||
func runRoundTrip(t *testing.T, dropEvery uint64) {
|
||||
t.Helper()
|
||||
|
||||
clientConn, serverConn := pipePair(dropEvery)
|
||||
profile := DefaultProfile()
|
||||
|
||||
accepted := make(chan *smux.Session, 1)
|
||||
serverErr := make(chan error, 1)
|
||||
go func() {
|
||||
kcpSess, err := Accept(serverConn, profile)
|
||||
if err != nil {
|
||||
serverErr <- err
|
||||
return
|
||||
}
|
||||
smuxSess, err := smux.Server(kcpSess, SmuxConfig())
|
||||
if err != nil {
|
||||
serverErr <- err
|
||||
return
|
||||
}
|
||||
accepted <- smuxSess
|
||||
}()
|
||||
|
||||
kcpClient, err := Dial(clientConn, profile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = kcpClient.Close() }()
|
||||
|
||||
smuxClient, err := smux.Client(kcpClient, SmuxConfig())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = smuxClient.Close() }()
|
||||
|
||||
stream, err := smuxClient.OpenStream()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = stream.Close() }()
|
||||
|
||||
payload := make([]byte, 256*1024)
|
||||
if _, rerr := rand.Read(payload); rerr != nil {
|
||||
t.Fatal(rerr)
|
||||
}
|
||||
writeErr := make(chan error, 1)
|
||||
go func() { _, werr := stream.Write(payload); writeErr <- werr }()
|
||||
|
||||
var smuxServer *smux.Session
|
||||
select {
|
||||
case smuxServer = <-accepted:
|
||||
case serr := <-serverErr:
|
||||
t.Fatal(serr)
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("server accept timeout")
|
||||
}
|
||||
defer func() { _ = smuxServer.Close() }()
|
||||
|
||||
srvStream, err := smuxServer.AcceptStream()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = srvStream.Close() }()
|
||||
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(srvStream, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatal("payload mismatch client->server")
|
||||
}
|
||||
if err := <-writeErr; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// обратное направление: сервер отвечает по тому же потоку
|
||||
back := payload[:4096]
|
||||
go func() { _, _ = srvStream.Write(back) }()
|
||||
echo := make([]byte, len(back))
|
||||
if err := stream.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := io.ReadFull(stream, echo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(echo, back) {
|
||||
t.Fatal("payload mismatch server->client")
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ type Config struct {
|
||||
Provider string
|
||||
Peer string
|
||||
Transport string
|
||||
Mode string
|
||||
ObfProfile string
|
||||
ObfKey string
|
||||
N int
|
||||
@@ -26,6 +27,7 @@ type Config struct {
|
||||
DNSMode string
|
||||
DNSServers string
|
||||
ManualCaptcha bool
|
||||
KCP *KCP
|
||||
Comment string
|
||||
}
|
||||
|
||||
@@ -35,6 +37,7 @@ type wire struct {
|
||||
Provider string `json:"provider"`
|
||||
Peer string `json:"peer"`
|
||||
Transport string `json:"transport,omitempty"`
|
||||
Mode string `json:"mode,omitempty"`
|
||||
Obf string `json:"obf,omitempty"`
|
||||
Key string `json:"key,omitempty"`
|
||||
N int `json:"n,omitempty"`
|
||||
@@ -44,6 +47,7 @@ type wire struct {
|
||||
DNSMode string `json:"dns,omitempty"`
|
||||
DNSServers string `json:"dnss,omitempty"`
|
||||
ManualCaptcha bool `json:"mcap,omitempty"`
|
||||
KCP *KCP `json:"kcp,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
@@ -81,6 +85,7 @@ func Parse(s string) (*Config, error) {
|
||||
Provider: w.Provider,
|
||||
Peer: w.Peer,
|
||||
Transport: w.Transport,
|
||||
Mode: w.Mode,
|
||||
ObfProfile: w.Obf,
|
||||
ObfKey: w.Key,
|
||||
N: w.N,
|
||||
@@ -90,6 +95,7 @@ func Parse(s string) (*Config, error) {
|
||||
DNSMode: w.DNSMode,
|
||||
DNSServers: w.DNSServers,
|
||||
ManualCaptcha: w.ManualCaptcha,
|
||||
KCP: w.KCP,
|
||||
Comment: w.Name,
|
||||
}, nil
|
||||
}
|
||||
@@ -101,6 +107,7 @@ func (c *Config) String() string {
|
||||
Provider: c.Provider,
|
||||
Peer: c.Peer,
|
||||
Transport: c.Transport,
|
||||
Mode: c.Mode,
|
||||
N: c.N,
|
||||
StreamsPerCred: c.StreamsPerCred,
|
||||
ClientID: c.ClientID,
|
||||
@@ -108,6 +115,7 @@ func (c *Config) String() string {
|
||||
DNSMode: c.DNSMode,
|
||||
DNSServers: c.DNSServers,
|
||||
ManualCaptcha: c.ManualCaptcha,
|
||||
KCP: c.KCP,
|
||||
Name: c.Comment,
|
||||
}
|
||||
if c.ObfProfile != "" && c.ObfProfile != "none" {
|
||||
@@ -121,3 +129,14 @@ func (c *Config) String() string {
|
||||
}
|
||||
return scheme + base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
type KCP struct {
|
||||
NoDelay int `json:"nodelay"`
|
||||
Interval int `json:"interval"`
|
||||
Resend int `json:"resend"`
|
||||
NC int `json:"nc"`
|
||||
SndWnd int `json:"sndwnd"`
|
||||
RcvWnd int `json:"rcvwnd"`
|
||||
MTU int `json:"mtu"`
|
||||
ACKNoDelay bool `json:"acknodelay"`
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package uri
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -17,6 +18,7 @@ func TestRoundTrip(t *testing.T) {
|
||||
Provider: "vk",
|
||||
Peer: "127.0.0.1:56000",
|
||||
Transport: "udp",
|
||||
Mode: "tcp",
|
||||
ObfProfile: "rtpopus",
|
||||
ObfKey: "d823fa",
|
||||
N: 16,
|
||||
@@ -96,3 +98,56 @@ func TestParseErrors(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Ссылка без mode - от старого клиента; поле optional, режим остаётся дефолтным.
|
||||
func TestParseLegacyLinkWithoutMode(t *testing.T) {
|
||||
legacy := (&Config{Version: currentVersion, Provider: "vk", Peer: "1.2.3.4:56000"}).String()
|
||||
got, err := Parse(legacy)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Mode != "" {
|
||||
t.Errorf("Mode = %q, want empty", got.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
// Владелец мог затюнить ARQ на сервере - гостю нужен тот же профиль, иначе разъедутся MTU.
|
||||
func TestKCPRoundTrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
in := &Config{
|
||||
Version: currentVersion,
|
||||
Provider: "vk",
|
||||
Peer: "1.2.3.4:56000",
|
||||
Mode: "tcp",
|
||||
KCP: &KCP{NoDelay: 1, Interval: 40, Resend: 2, NC: 1, SndWnd: 256, RcvWnd: 256, MTU: 1100},
|
||||
}
|
||||
|
||||
out, err := Parse(in.String())
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if out.KCP == nil {
|
||||
t.Fatal("KCP dropped by round-trip")
|
||||
}
|
||||
if *out.KCP != *in.KCP {
|
||||
t.Errorf("KCP = %+v, want %+v", *out.KCP, *in.KCP)
|
||||
}
|
||||
}
|
||||
|
||||
// Ссылка без kcp - от старого клиента: профиль остаётся дефолтным, поле опционально.
|
||||
func TestKCPAbsentStaysNil(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
link := (&Config{Version: currentVersion, Provider: "vk", Peer: "1.2.3.4:56000"}).String()
|
||||
if strings.Contains(link, "kcp") {
|
||||
t.Error("empty KCP must not be serialized")
|
||||
}
|
||||
out, err := Parse(link)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if out.KCP != nil {
|
||||
t.Errorf("KCP = %+v, want nil", out.KCP)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package wire
|
||||
|
||||
import (
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var relayBufPool = sync.Pool{
|
||||
New: func() any {
|
||||
b := make([]byte, 1600+128)
|
||||
return &b
|
||||
},
|
||||
}
|
||||
|
||||
// RelayPacketConn адаптирует net.PacketConn релея с опциональным шифрованием/обфускацией.
|
||||
type RelayPacketConn struct {
|
||||
Relay net.PacketConn
|
||||
Peer net.Addr
|
||||
Codec Codec
|
||||
}
|
||||
|
||||
func (r *RelayPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
if r.Codec == nil {
|
||||
return r.Relay.ReadFrom(b)
|
||||
}
|
||||
bp := relayBufPool.Get().(*[]byte) //nolint:errcheck // pool New always returns *[]byte
|
||||
buf := *bp
|
||||
need := r.Codec.MaxWire(len(b))
|
||||
if cap(buf) < need {
|
||||
buf = make([]byte, need)
|
||||
*bp = buf
|
||||
}
|
||||
defer relayBufPool.Put(bp)
|
||||
|
||||
n, addr, err := r.Relay.ReadFrom(buf[:cap(buf)])
|
||||
if err != nil {
|
||||
return 0, addr, err
|
||||
}
|
||||
m, err := r.Codec.Unwrap(buf[:n], b)
|
||||
if err != nil {
|
||||
return 0, addr, err
|
||||
}
|
||||
return m, addr, nil
|
||||
}
|
||||
|
||||
func (r *RelayPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
||||
if r.Codec == nil {
|
||||
return r.Relay.WriteTo(b, r.Peer)
|
||||
}
|
||||
wireLen := r.Codec.MaxWire(len(b))
|
||||
|
||||
bp := relayBufPool.Get().(*[]byte) //nolint:errcheck // pool New always returns *[]byte
|
||||
out := *bp
|
||||
if cap(out) < wireLen {
|
||||
out = make([]byte, wireLen)
|
||||
*bp = out
|
||||
}
|
||||
out = out[:wireLen]
|
||||
defer relayBufPool.Put(bp)
|
||||
|
||||
n, err := r.Codec.WrapInto(out, b)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err = r.Relay.WriteTo(out[:n], r.Peer); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
func (r *RelayPacketConn) Close() error { return r.Relay.Close() }
|
||||
func (r *RelayPacketConn) LocalAddr() net.Addr { return r.Relay.LocalAddr() }
|
||||
func (r *RelayPacketConn) SetDeadline(t time.Time) error { return r.Relay.SetDeadline(t) }
|
||||
func (r *RelayPacketConn) SetReadDeadline(t time.Time) error { return r.Relay.SetReadDeadline(t) }
|
||||
func (r *RelayPacketConn) SetWriteDeadline(t time.Time) error { return r.Relay.SetWriteDeadline(t) }
|
||||
+17
-1
@@ -49,7 +49,7 @@ func Version() string
|
||||
"clientId": "0123456789abcdef0123456789abcdef",
|
||||
"provider": "vk",
|
||||
"turn": {"n": 12, "transport": "tcp", "host": "", "port": ""},
|
||||
"proxy": {"listen": "127.0.0.1:9000"},
|
||||
"proxy": {"mode": "udp", "listen": "127.0.0.1:9000"},
|
||||
"vk": {"links": ["https://vk.ru/call/join/..."], "streamsPerCred": 12,
|
||||
"manualCaptcha": false, "platform": "mobile"},
|
||||
"obf": {"profile": "rtpopus3", "key": "<64 hex>", "timingMs": 0},
|
||||
@@ -62,6 +62,22 @@ func Version() string
|
||||
|
||||
* `clientId` - обязателен. Ядро на мобиле не пишет файлы, ID должен храниться в приложении.
|
||||
|
||||
### Режим туннеля
|
||||
|
||||
`proxy.mode`: `udp` (по умолчанию, UDP-релей для WireGuard) или `tcp` (TCP-форвардер для Xray/sing-box).
|
||||
|
||||
В `tcp` ядро слушает `proxy.listen` как TCP-порт, и VLESS-клиент ходит туда своим outbound. Своего tun при этом нет:
|
||||
|
||||
* запускать через `Start(configJSON)`, не через `StartTunnel`; `VpnService.prepare`/`establish` звать не нужно - иначе tun отбирается у чужого VPN;
|
||||
* `protect()` не применяется, поэтому трафик до TURN пойдёт через активный системный VPN, если он включён;
|
||||
* `TunnelStats()` не наполняется, счётчики отдаёт `GetState()`, `connected`/`total` считаются по сессиям пула так же, как в udp-режиме;
|
||||
* `proxy.mode: "tcp"` вместе с `tunnel.mode` `wg`/`awg` отклоняется валидацией: встроенный WG гонит датаграммы;
|
||||
* `StartTunnel` при `proxy.mode: "tcp"` возвращает `ErrTCPModeRequiresStart` - ядро tun не читает, и принятый fd остался бы установленным вхолостую.
|
||||
|
||||
Опциональная секция `kcp` (`noDelay`, `interval`, `resend`, `nc`, `sndWnd`, `rcvWnd`, `mtu`, `ackNoDelay`) тюнит ARQ tcp-режима; в `udp` любое отличие от дефолта - ошибка. Дефолт агрессивный (`interval: 20`, окна 512, `ackNoDelay: true`), для мобильной сети щадящий вариант - `interval: 40`, окна 256, `ackNoDelay: false`.
|
||||
|
||||
JSON парсится с `DisallowUnknownFields`, поэтому конфиг с `proxy.mode`/`kcp` требует aar с этим изменением; старый JSON без них новое ядро читает как `udp`.
|
||||
|
||||
### Туннелирование
|
||||
|
||||
`tunnel.mode` принимает значения `none`, `wg` (WireGuard) или `awg` (AmneziaWG).
|
||||
|
||||
@@ -40,6 +40,10 @@ const (
|
||||
|
||||
var ErrTunnelRequiresStartTunnel = errors.New("tunnel mode requires StartTunnel with a platform tun fd")
|
||||
|
||||
// ErrTCPModeRequiresStart - в tcp-режиме ядро слушает локальный порт и tun не читает:
|
||||
// принятый fd остался бы установленным вхолостую, а трафик устройства - в чёрной дыре.
|
||||
var ErrTCPModeRequiresStart = errors.New("proxy mode tcp requires Start without a tun fd")
|
||||
|
||||
var version = "dev"
|
||||
|
||||
func Version() string { return version }
|
||||
@@ -243,6 +247,9 @@ func startLocked(configJSON string, tunFD int, withTunnel bool) error {
|
||||
if cfg.Tunnel.Enabled() && !withTunnel {
|
||||
return fmt.Errorf("%w (mode=%s)", ErrTunnelRequiresStartTunnel, cfg.Tunnel.Mode)
|
||||
}
|
||||
if withTunnel && cfg.Proxy.Mode == config.ProxyModeTCP {
|
||||
return ErrTCPModeRequiresStart
|
||||
}
|
||||
|
||||
logger := &sinkLogger{debug: cfg.Log.Debug, buf: sharedLogBuf}
|
||||
|
||||
|
||||
@@ -185,3 +185,24 @@ func TestRestartReplacesSession(t *testing.T) {
|
||||
t.Errorf("GetState().State = %q, want running session", got)
|
||||
}
|
||||
}
|
||||
|
||||
// tcp-режим не требует tun: приложение зовёт Start, а не StartTunnel.
|
||||
func TestTCPModeConfig(t *testing.T) {
|
||||
const tcpConfig = `{"peer":"1.2.3.4:5000","clientId":"deadbeef","proxy":{"mode":"tcp"},"vk":{"links":["https://vk.ru/call/join/CODE"]}}`
|
||||
if msg := ValidateConfig(tcpConfig); msg != "" {
|
||||
t.Errorf("ValidateConfig(tcp) = %q, want empty", msg)
|
||||
}
|
||||
args, err := ConfigToArgs(tcpConfig)
|
||||
if err != nil {
|
||||
t.Fatalf("ConfigToArgs() error = %v", err)
|
||||
}
|
||||
if !strings.Contains(args, "-mode tcp") {
|
||||
t.Errorf("ConfigToArgs() = %q, missing -mode tcp", args)
|
||||
}
|
||||
|
||||
tcpWithTunnel := `{"peer":"1.2.3.4:5000","clientId":"deadbeef","proxy":{"mode":"tcp"},` +
|
||||
`"tunnel":{"mode":"wg","config":"[Interface]","mtu":1280},"vk":{"links":["https://vk.ru/call/join/CODE"]}}`
|
||||
if msg := ValidateConfig(tcpWithTunnel); msg == "" {
|
||||
t.Error("ValidateConfig(tcp+wg) = \"\", want error")
|
||||
}
|
||||
}
|
||||
@@ -220,3 +220,11 @@ func TestClampToInt64Overflow(t *testing.T) {
|
||||
t.Errorf("clampToInt64(MaxInt64) = %d, want MaxInt64", got)
|
||||
}
|
||||
}
|
||||
|
||||
// В tcp-режиме ядро tun не читает: принятый fd остался бы установленным вхолостую.
|
||||
func TestStartTunnelRejectsTCPMode(t *testing.T) {
|
||||
const cfg = `{"peer":"1.2.3.4:5000","clientId":"deadbeef","proxy":{"mode":"tcp"},"vk":{"links":["https://vk.ru/call/join/CODE"]}}`
|
||||
if err := StartTunnel(cfg, 7); !errors.Is(err, ErrTCPModeRequiresStart) {
|
||||
t.Fatalf("StartTunnel() error = %v, want ErrTCPModeRequiresStart", err)
|
||||
}
|
||||
}
|
||||
+33
-13
@@ -25,7 +25,7 @@ readonly COMPOSE_FILE="${APP_DIR}/docker-compose.yml"
|
||||
readonly CONTAINER="free-turn-proxy"
|
||||
readonly GUM_VERSION="0.17.0" # pinned; при сбое скачивания — fallback на latest API
|
||||
|
||||
# WireGuard bootstrap (опциональный)
|
||||
# WireGuard bootstrap (опциональный, только mode=udp)
|
||||
readonly WG_DIR="/etc/wireguard"
|
||||
readonly WG_IFACE="wg0"
|
||||
readonly WG_CONF="${WG_DIR}/${WG_IFACE}.conf"
|
||||
@@ -52,6 +52,7 @@ readonly C_RED='\033[0;31m' C_GREEN='\033[0;32m' C_YELLOW='\033[1;33m' C_CYAN='\
|
||||
INSTALL_METHOD="docker" # docker | systemd
|
||||
VERSION="latest"
|
||||
PROVIDER="vk" # vk (источник TURN-creds на клиенте; сервер provider-agnostic)
|
||||
PROXY_MODE="udp" # udp | tcp
|
||||
BACKEND_PORT=""
|
||||
LISTEN_PORT="56000"
|
||||
OBF_PROFILE="rtpopus" # rtpopus | none
|
||||
@@ -333,6 +334,7 @@ save_config() {
|
||||
INSTALL_METHOD="$INSTALL_METHOD"
|
||||
VERSION="$VERSION"
|
||||
PROVIDER="$PROVIDER"
|
||||
PROXY_MODE="$PROXY_MODE"
|
||||
BACKEND_PORT="$BACKEND_PORT"
|
||||
LISTEN_PORT="$LISTEN_PORT"
|
||||
OBF_PROFILE="$OBF_PROFILE"
|
||||
@@ -356,8 +358,9 @@ connect_addr() { echo "127.0.0.1:${BACKEND_PORT}"; }
|
||||
validate_config() {
|
||||
case "$INSTALL_METHOD" in docker | systemd) ;; *) die "method: docker|systemd, а не '$INSTALL_METHOD'" ;; esac
|
||||
case "$PROVIDER" in vk) ;; *) die "provider: vk, а не '$PROVIDER'" ;; esac
|
||||
case "$PROXY_MODE" in udp | tcp) ;; *) die "mode: udp|tcp, а не '$PROXY_MODE'" ;; esac
|
||||
valid_port "$LISTEN_PORT" || die "listen-port невалиден: '$LISTEN_PORT'"
|
||||
[ -z "$BACKEND_PORT" ] && BACKEND_PORT="51820"
|
||||
[ -z "$BACKEND_PORT" ] && { [ "$PROXY_MODE" = "udp" ] && BACKEND_PORT="51820" || BACKEND_PORT="443"; }
|
||||
valid_port "$BACKEND_PORT" || die "backend-port невалиден: '$BACKEND_PORT'"
|
||||
case "$OBF_PROFILE" in
|
||||
rtpopus)
|
||||
@@ -367,6 +370,7 @@ validate_config() {
|
||||
*) die "obf: rtpopus|none, а не '$OBF_PROFILE'" ;;
|
||||
esac
|
||||
if [ "$WG_SETUP" = "1" ]; then
|
||||
[ "$PROXY_MODE" = "udp" ] || die "WireGuard bootstrap доступен только при -mode udp."
|
||||
valid_endpoint "$WG_ENDPOINT" || die "wg-endpoint невалиден (host:port): '$WG_ENDPOINT'"
|
||||
fi
|
||||
return 0
|
||||
@@ -381,6 +385,12 @@ wizard_method() {
|
||||
systemd "Systemd (бинарь напрямую)"
|
||||
}
|
||||
|
||||
wizard_mode() {
|
||||
ui_menu PROXY_MODE "Режим туннеля:" "$PROXY_MODE" \
|
||||
udp "UDP-relay · WireGuard / AmneziaWG" \
|
||||
tcp "TCP-forward · Xray / sing-box"
|
||||
}
|
||||
|
||||
wizard_provider() {
|
||||
ui_menu PROVIDER "Провайдер TURN-creds (клиент):" "$PROVIDER" \
|
||||
vk "VK Calls API"
|
||||
@@ -388,19 +398,23 @@ wizard_provider() {
|
||||
|
||||
wizard_ports() {
|
||||
detect_wg_port
|
||||
local def_backend="$BACKEND_PORT"
|
||||
local def_backend="$BACKEND_PORT" label="Порт вашего VPN / бэкенда"
|
||||
if [ -z "$def_backend" ]; then
|
||||
if [ -n "$WG_PORT" ]; then
|
||||
if [ "$PROXY_MODE" = "udp" ] && [ -n "$WG_PORT" ]; then
|
||||
def_backend="$WG_PORT"; log_info "Найден WireGuard на порту $WG_PORT."
|
||||
else
|
||||
def_backend="51820"
|
||||
fi
|
||||
elif [ "$PROXY_MODE" = "udp" ]; then def_backend="51820"
|
||||
else def_backend="443"; fi
|
||||
fi
|
||||
ask_port BACKEND_PORT "Порт вашего VPN / бэкенда" "$def_backend"
|
||||
if [ "$PROXY_MODE" = "tcp" ]; then
|
||||
label="Порт TCP-бэкенда (Xray / sing-box inbound)"
|
||||
ui_note "TCP-режим" "Backend — ваш Xray/sing-box inbound на 127.0.0.1. Сервис поднимаете отдельно; инсталлятор его не ставит."
|
||||
fi
|
||||
ask_port BACKEND_PORT "$label" "$def_backend"
|
||||
ask_port LISTEN_PORT "Внешний порт (приём Free Turn Proxy)" "${LISTEN_PORT:-56000}"
|
||||
}
|
||||
|
||||
wizard_wireguard() {
|
||||
[ "$PROXY_MODE" = "udp" ] || { WG_SETUP=0; return; }
|
||||
if [ -n "$WG_PORT" ]; then
|
||||
log_info "Обнаружен WireGuard (порт $WG_PORT) — использую существующий."
|
||||
WG_SETUP=0; return
|
||||
@@ -489,6 +503,7 @@ review_config() {
|
||||
| Метод | $INSTALL_METHOD |
|
||||
| Версия | $VERSION |
|
||||
| Провайдер | $PROVIDER |
|
||||
| Режим | $PROXY_MODE |
|
||||
| Порт бэкенда | 127.0.0.1:$BACKEND_PORT |
|
||||
| Внешний порт | 0.0.0.0:$LISTEN_PORT |
|
||||
| Обфускация | $obf_line |
|
||||
@@ -496,13 +511,14 @@ review_config() {
|
||||
| WireGuard | $wg_line |
|
||||
EOF
|
||||
else
|
||||
echo; log_info "Настройки: method=$INSTALL_METHOD version=$VERSION provider=$PROVIDER backend=$BACKEND_PORT listen=$LISTEN_PORT obf=$obf_line auth=$auth_line wireguard=$wg_line"
|
||||
echo; log_info "Настройки: method=$INSTALL_METHOD version=$VERSION provider=$PROVIDER mode=$PROXY_MODE backend=$BACKEND_PORT listen=$LISTEN_PORT obf=$obf_line auth=$auth_line wireguard=$wg_line"
|
||||
fi
|
||||
ui_yesno "Применить эти настройки?" "Y" || ui_abort
|
||||
}
|
||||
|
||||
wizard() {
|
||||
wizard_method
|
||||
wizard_mode
|
||||
wizard_provider
|
||||
wizard_ports
|
||||
wizard_wireguard
|
||||
@@ -669,6 +685,7 @@ apply_docker() {
|
||||
echo " environment:"
|
||||
echo " - CONNECT_ADDR=$(connect_addr)"
|
||||
echo " - LISTEN_ADDR=0.0.0.0:${LISTEN_PORT}"
|
||||
echo " - MODE=${PROXY_MODE}"
|
||||
echo " - OBF_PROFILE=${OBF_PROFILE}"
|
||||
[ "$OBF_PROFILE" != "none" ] && echo " - OBF_KEY=${OBF_KEY}"
|
||||
if [ -n "$CLIENTS_FILE_CONF" ]; then
|
||||
@@ -705,7 +722,7 @@ healthcheck_systemd() {
|
||||
|
||||
apply_systemd() {
|
||||
download_binary
|
||||
local args; args="-listen 0.0.0.0:${LISTEN_PORT} -connect $(connect_addr)"
|
||||
local args; args="-listen 0.0.0.0:${LISTEN_PORT} -connect $(connect_addr) -mode ${PROXY_MODE}"
|
||||
[ "$OBF_PROFILE" != "none" ] && args="$args -obf-profile ${OBF_PROFILE} -obf-key ${OBF_KEY}"
|
||||
[ -n "$CLIENTS_FILE_CONF" ] && args="$args -clients-file ${CLIENTS_FILE_CONF}"
|
||||
cat > "$UNIT_FILE" <<EOF
|
||||
@@ -757,6 +774,7 @@ print_summary() {
|
||||
echo "|---|---|"
|
||||
echo "| **Сервер (peer)** | \`${ext_ip}:${LISTEN_PORT}\` |"
|
||||
echo "| **Провайдер** | ${PROVIDER} (клиент: \`-provider ${PROVIDER}\`) |"
|
||||
echo "| **Режим** | ${PROXY_MODE} |"
|
||||
echo "| **Версия** | ${VERSION} |"
|
||||
echo "| **Метод** | ${INSTALL_METHOD} |"
|
||||
[ "$OBF_PROFILE" != "none" ] && echo "| **Обфускация** | ${OBF_PROFILE} |"
|
||||
@@ -783,7 +801,7 @@ print_summary() {
|
||||
echo "--------------------------------------------------------"
|
||||
echo "Сервер (peer): ${ext_ip}:${LISTEN_PORT}"
|
||||
echo "Провайдер (клиент): -provider ${PROVIDER}"
|
||||
echo "Версия: ${VERSION} | Метод: ${INSTALL_METHOD}"
|
||||
echo "Режим: ${PROXY_MODE} | Версия: ${VERSION} | Метод: ${INSTALL_METHOD}"
|
||||
[ "$OBF_PROFILE" != "none" ] && echo "Обфускация: ${OBF_PROFILE} | Ключ: ${OBF_KEY}"
|
||||
[ -n "$CLIENTS_FILE_CONF" ] && { echo "Client ID auth включён. Добавить клиента:"; echo " $add_cmd"; }
|
||||
[ "$WG_SETUP" = "1" ] && echo "WireGuard поднят. Клиентский конфиг: $WG_CLIENT_CONF (Endpoint $WG_ENDPOINT, готов)."
|
||||
@@ -868,7 +886,8 @@ Free Turn Proxy — установщик сервера.
|
||||
-y, --yes, --non-interactive без вопросов
|
||||
--method docker|systemd метод (default docker)
|
||||
--provider vk провайдер TURN-creds для клиента (default vk)
|
||||
--backend-port N порт бэкенда (default 51820)
|
||||
--mode udp|tcp режим (default udp)
|
||||
--backend-port N порт бэкенда (default udp→51820 / tcp→443)
|
||||
--listen-port N внешний порт (default 56000)
|
||||
--obf rtpopus|none обфускация (default rtpopus)
|
||||
--obf-key HEX64 ключ (нет → сгенерируется)
|
||||
@@ -882,7 +901,7 @@ Free Turn Proxy — установщик сервера.
|
||||
-h, --help
|
||||
|
||||
Примеры:
|
||||
sudo bash install.sh -y --method docker --backend-port 51820
|
||||
sudo bash install.sh -y --method docker --mode udp --backend-port 51820
|
||||
sudo bash install.sh -y --update --version v1.2.3
|
||||
sudo bash install.sh -y --uninstall --purge
|
||||
EOF
|
||||
@@ -902,6 +921,7 @@ parse_args() {
|
||||
vk) OVERRIDES+=("PROVIDER=${2}") ;;
|
||||
*) die "--provider: vk" ;;
|
||||
esac; shift ;;
|
||||
--mode) OVERRIDES+=("PROXY_MODE=${2:-}"); shift ;;
|
||||
--backend-port) OVERRIDES+=("BACKEND_PORT=${2:-}"); shift ;;
|
||||
--listen-port) OVERRIDES+=("LISTEN_PORT=${2:-}"); shift ;;
|
||||
--obf) OVERRIDES+=("OBF_PROFILE=${2:-}"); shift ;;
|
||||
|
||||
Reference in new issue
Block a user