feat(client): провайдер direct - прямо на сервер без TURN-реле
Тот же DTLS с обфускацией, сервер не меняется. По умолчанию один поток.
This commit is contained in:
1 parent
7df3a3fd91
commit
ee30afc922
17 files changed
+244
-102
No files matched your search
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
"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"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/turndial"
|
||||
)
|
||||
@@ -56,8 +55,8 @@ func TestMaintainSessionReportsFatal(t *testing.T) {
|
||||
auth := &fakeAuth{}
|
||||
deps := &Deps{Log: logx.Nop(), Auth: auth}
|
||||
params := &Params{
|
||||
GetCreds: func(context.Context, int) (string, string, []string, error) {
|
||||
return "", "", nil, provider.ErrFatalNoStreams
|
||||
Dial: func(context.Context, int) (*turndial.Stream, error) {
|
||||
return nil, provider.ErrFatalNoStreams
|
||||
},
|
||||
}
|
||||
|
||||
@@ -66,7 +65,7 @@ func TestMaintainSessionReportsFatal(t *testing.T) {
|
||||
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 })
|
||||
1, newSessionPool(nil), func(err error) { fatalCh <- err })
|
||||
}()
|
||||
|
||||
select {
|
||||
@@ -98,8 +97,8 @@ func TestMaintainSessionHandlesAuthError(t *testing.T) {
|
||||
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
|
||||
Dial: func(context.Context, int) (*turndial.Stream, error) {
|
||||
return nil, authErr
|
||||
},
|
||||
}
|
||||
|
||||
@@ -107,7 +106,7 @@ func TestMaintainSessionHandlesAuthError(t *testing.T) {
|
||||
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) {})
|
||||
1, newSessionPool(nil), func(error) {})
|
||||
}()
|
||||
|
||||
deadline := time.Now().Add(15 * time.Second)
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"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"
|
||||
@@ -40,20 +39,17 @@ const (
|
||||
// ErrFatal возвращается при фатальных ошибках провайдера, требующих остановки клиента.
|
||||
var ErrFatal = errors.New("tcprelay: fatal error")
|
||||
|
||||
// GetCredsFunc переиспользуется из udprelay: контракт с провайдером один на оба режима.
|
||||
type GetCredsFunc = udprelay.GetCredsFunc
|
||||
// DialFunc переиспользуется из udprelay: подъём потока один на оба режима.
|
||||
type DialFunc = udprelay.DialFunc
|
||||
|
||||
// AuthHandler переиспользуется из udprelay: жизненный цикл реквизитов один на оба режима.
|
||||
type AuthHandler = udprelay.AuthHandler
|
||||
|
||||
type Params struct {
|
||||
Host string
|
||||
Port string
|
||||
TransportUDP bool
|
||||
Dial DialFunc
|
||||
Profile string
|
||||
ObfKey []byte
|
||||
ObfTiming time.Duration
|
||||
GetCreds GetCredsFunc
|
||||
KCPProfile kcpmux.Profile
|
||||
ClientID string
|
||||
TrafficStats *stats.Stats
|
||||
@@ -79,19 +75,11 @@ func (d *Deps) log() logx.Logger {
|
||||
|
||||
func (d *Deps) auth() AuthHandler {
|
||||
if d.Auth == nil {
|
||||
return nopAuth{}
|
||||
return udprelay.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 {
|
||||
@@ -99,7 +87,6 @@ func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, lis
|
||||
}
|
||||
log := deps.log()
|
||||
pool := newSessionPool(deps.ConnectedStreams)
|
||||
pacer := allocpace.New(allocpace.DefaultInterval)
|
||||
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
@@ -126,7 +113,7 @@ func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, lis
|
||||
for i := range numSessions {
|
||||
id := i + 1
|
||||
wgBG.Go(func() {
|
||||
_ = safego.Run(log, func() { maintainSession(runCtx, deps, params, peer, id, pool, pacer, fatal) })
|
||||
_ = safego.Run(log, func() { maintainSession(runCtx, deps, params, peer, id, pool, fatal) })
|
||||
})
|
||||
}
|
||||
if deps.Recycle != nil {
|
||||
@@ -279,11 +266,11 @@ type session 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)) {
|
||||
func maintainSession(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, id int, pool *sessionPool, fatal func(error)) {
|
||||
log := deps.log()
|
||||
auth := deps.auth()
|
||||
for ctx.Err() == nil {
|
||||
s, err := createSession(ctx, deps, params, peer, id, pacer)
|
||||
s, err := createSession(ctx, deps, params, peer, id)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
@@ -361,7 +348,7 @@ func awaitDead(ctx context.Context, log logx.Logger, s *session, id int) bool {
|
||||
}
|
||||
|
||||
// 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) {
|
||||
func createSession(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, id int) (*session, error) {
|
||||
log := deps.log()
|
||||
var closers []func()
|
||||
cleanup := func() {
|
||||
@@ -370,10 +357,7 @@ func createSession(ctx context.Context, deps *Deps, params *Params, peer *net.UD
|
||||
}
|
||||
}
|
||||
|
||||
if !pacer.Wait(ctx) {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
stream, err := udprelay.DialTURN(ctx, params.Host, params.Port, params.TransportUDP, peer, id, params.GetCreds, log)
|
||||
stream, err := params.Dial(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/turndial"
|
||||
)
|
||||
|
||||
type DialFunc func(ctx context.Context, streamID int) (*turndial.Stream, error)
|
||||
|
||||
// GetCredsFunc разрешает TURN-реквизиты для streamID.
|
||||
type GetCredsFunc func(ctx context.Context, streamID int) (user, pass string, rawURLs []string, err error)
|
||||
|
||||
|
||||
@@ -74,9 +74,6 @@ func TURNLoop(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case pair := <-connchan:
|
||||
if !deps.allocPace.Wait(ctx) {
|
||||
return
|
||||
}
|
||||
c := make(chan error, 1)
|
||||
go deps.guard(func() { oneTURN(ctx, deps, params, peer, pair.pipe, streamID, c) })()
|
||||
|
||||
@@ -234,7 +231,7 @@ func oneTURN(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
|
||||
c <- err
|
||||
}()
|
||||
|
||||
stream, derr := DialTURN(ctx, params.Host, params.Port, params.TransportUDP, peer, streamID, params.GetCreds, deps.log())
|
||||
stream, derr := params.Dial(ctx, streamID)
|
||||
if derr != nil {
|
||||
if deps.Auth.IsAuthError(derr) {
|
||||
deps.Auth.HandleAuthError(streamID)
|
||||
|
||||
@@ -11,7 +11,6 @@ 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"
|
||||
@@ -26,21 +25,26 @@ type AuthHandler interface {
|
||||
BackoffUntilUnix() int64
|
||||
}
|
||||
|
||||
// Params содержит конфигурацию подключения к TURN и параметры обфускации.
|
||||
// Params содержит способ подъёма потока и параметры обфускации.
|
||||
type Params struct {
|
||||
Host string
|
||||
Port string
|
||||
TransportUDP bool
|
||||
Dial DialFunc
|
||||
Profile string
|
||||
ObfKey []byte
|
||||
ObfTiming time.Duration
|
||||
GetCreds GetCredsFunc
|
||||
ClientID string
|
||||
TrafficStats *stats.Stats
|
||||
}
|
||||
|
||||
const streamStartBarrier = 20 * time.Second
|
||||
|
||||
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 }
|
||||
|
||||
// ErrFatal возвращается при фатальных ошибках провайдера, требующих остановки клиента.
|
||||
var ErrFatal = errors.New("udprelay: fatal error")
|
||||
|
||||
@@ -52,7 +56,6 @@ type Deps struct {
|
||||
ConnectedStreams *atomic.Int32
|
||||
OnTURNServer func(ip net.IP)
|
||||
fatalCh chan error
|
||||
allocPace *allocpace.Pacer
|
||||
}
|
||||
|
||||
func (d *Deps) log() logx.Logger {
|
||||
@@ -93,7 +96,6 @@ func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, log
|
||||
ConnectedStreams: connectedStreams,
|
||||
OnTURNServer: onTURNServer,
|
||||
fatalCh: fatalCh,
|
||||
allocPace: allocpace.New(allocpace.DefaultInterval),
|
||||
}
|
||||
|
||||
runCtx, runCancel := context.WithCancel(ctx)
|
||||
|
||||
@@ -14,16 +14,9 @@ import (
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/provider"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/safego"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/dtlsdial"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/turndial"
|
||||
)
|
||||
|
||||
type stubAuth struct{}
|
||||
|
||||
func (stubAuth) IsAuthError(error) bool { return false }
|
||||
func (stubAuth) HandleAuthError(int) bool { return false }
|
||||
func (stubAuth) ResetErrors(int) {}
|
||||
func (stubAuth) DropCredentials(int) {}
|
||||
func (stubAuth) BackoffUntilUnix() int64 { return 0 }
|
||||
|
||||
type deadlineRecorder struct {
|
||||
net.PacketConn
|
||||
mu sync.Mutex
|
||||
@@ -51,8 +44,8 @@ func runFatalDeps(t *testing.T) (*dtlsdial.Dialer, *Params, *net.UDPAddr, *deadl
|
||||
t.Cleanup(func() { _ = pipe.Close(); _ = peerSide.Close() })
|
||||
|
||||
params := &Params{
|
||||
GetCreds: func(context.Context, int) (string, string, []string, error) {
|
||||
return "", "", nil, provider.ErrFatalNoStreams
|
||||
Dial: func(context.Context, int) (*turndial.Stream, error) {
|
||||
return nil, provider.ErrFatalNoStreams
|
||||
},
|
||||
}
|
||||
return &dtlsdial.Dialer{HandshakeTimeout: 100 * time.Millisecond},
|
||||
@@ -70,7 +63,7 @@ func TestRunReturnsOnFatalProviderError(t *testing.T) {
|
||||
var connected atomic.Int32
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- Run(context.Background(), dialer, stubAuth{}, logx.Nop(), &connected, nil, params, peer, local, 1)
|
||||
done <- Run(context.Background(), dialer, NopAuth{}, logx.Nop(), &connected, nil, params, peer, local, 1)
|
||||
}()
|
||||
|
||||
select {
|
||||
@@ -97,14 +90,14 @@ func TestRunReturnsOnFatalProviderError(t *testing.T) {
|
||||
func TestRunReturnsOnStreamPanic(t *testing.T) {
|
||||
t.Parallel()
|
||||
dialer, params, peer, local := runFatalDeps(t)
|
||||
params.GetCreds = func(context.Context, int) (string, string, []string, error) {
|
||||
params.Dial = func(context.Context, int) (*turndial.Stream, error) {
|
||||
panic("boom")
|
||||
}
|
||||
|
||||
var connected atomic.Int32
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- Run(context.Background(), dialer, stubAuth{}, logx.Nop(), &connected, nil, params, peer, local, 1)
|
||||
done <- Run(context.Background(), dialer, NopAuth{}, logx.Nop(), &connected, nil, params, peer, local, 1)
|
||||
}()
|
||||
|
||||
select {
|
||||
@@ -128,7 +121,7 @@ func TestRunFatalDoesNotWaitWarmupBarrier(t *testing.T) {
|
||||
done := make(chan error, 1)
|
||||
start := time.Now()
|
||||
go func() {
|
||||
done <- Run(context.Background(), dialer, stubAuth{}, logx.Nop(), &connected, nil, params, peer, local, 4)
|
||||
done <- Run(context.Background(), dialer, NopAuth{}, logx.Nop(), &connected, nil, params, peer, local, 4)
|
||||
}()
|
||||
|
||||
select {
|
||||
|
||||
Reference in new issue
Block a user