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
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user