feat(tcp): вернуть поддержку bond
This commit is contained in:
1 parent
a8b8363b79
commit
6f84a18b43
25 files changed
+1099
-10
No files matched your search
@@ -0,0 +1,79 @@
|
||||
package tcprelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/bond"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/stats"
|
||||
)
|
||||
|
||||
func proxyBond(ctx context.Context, log logx.Logger, conn net.Conn, pool *sessionPool) {
|
||||
defer func() { _ = conn.Close() }()
|
||||
lanes, traffic := openBondLanes(pool)
|
||||
defer func() {
|
||||
for _, lane := range lanes {
|
||||
_ = lane.Close()
|
||||
}
|
||||
}()
|
||||
if len(lanes) == 0 {
|
||||
return
|
||||
}
|
||||
stop := context.AfterFunc(ctx, func() {
|
||||
for _, lane := range lanes {
|
||||
_ = lane.Close()
|
||||
}
|
||||
})
|
||||
defer stop()
|
||||
var id [8]byte
|
||||
_, _ = rand.Read(id[:])
|
||||
deadline := time.Now().Add(bond.SetupTimeout)
|
||||
for i, lane := range lanes {
|
||||
h := bond.Hello{ID: binary.BigEndian.Uint64(id[:]), Index: uint16(i), Count: uint16(len(lanes))} //nolint:gosec // len(lanes) <= MaxLanes
|
||||
if err := helloBondLane(lane, h, deadline); err != nil {
|
||||
log.Debugf("TCP bond setup: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
log.Debugf("TCP bond connected: lanes=%d", len(lanes))
|
||||
if err := bond.Copy(ctx, conn, lanes, traffic); err != nil && ctx.Err() == nil {
|
||||
log.Debugf("TCP bond closed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func helloBondLane(lane net.Conn, h bond.Hello, deadline time.Time) error {
|
||||
if err := lane.SetWriteDeadline(deadline); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := bond.WriteHello(lane, h); err != nil {
|
||||
return err
|
||||
}
|
||||
return lane.SetWriteDeadline(time.Time{})
|
||||
}
|
||||
|
||||
func openBondLanes(pool *sessionPool) ([]net.Conn, *stats.Stats) {
|
||||
pool.mu.RLock()
|
||||
candidates := append([]*pooledSession(nil), pool.sessions...)
|
||||
pool.mu.RUnlock()
|
||||
lanes := make([]net.Conn, 0, len(candidates))
|
||||
var traffic *stats.Stats
|
||||
for _, ps := range candidates {
|
||||
if len(lanes) == bond.MaxLanes {
|
||||
break
|
||||
}
|
||||
if ps.sess.IsClosed() {
|
||||
continue
|
||||
}
|
||||
stream, err := ps.sess.OpenStream()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
lanes = append(lanes, stream)
|
||||
traffic = ps.traffic
|
||||
}
|
||||
return lanes, traffic
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package tcprelay
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"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/proxy/bond"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/tcpserver"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcpmux"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
func pairedBondSession(t *testing.T, ctx context.Context, server *bond.Server, backend string) *smux.Session {
|
||||
t.Helper()
|
||||
a, b := netconn.DatagramPipe(2048, 1024)
|
||||
t.Cleanup(func() { _ = a.Close(); _ = b.Close() })
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
tcpserver.HandleBond(ctx, logx.Nop(), b, backend, kcpmux.DefaultProfile(), server, "test-client")
|
||||
}()
|
||||
kcp, err := kcpmux.Dial(a, kcpmux.DefaultProfile())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess, err := smux.Client(kcp, kcpmux.SmuxConfig())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = sess.Close()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("bond server leaked")
|
||||
}
|
||||
})
|
||||
return sess
|
||||
}
|
||||
|
||||
func TestBondAcrossSessionsAndAfterSessionFailure(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second)
|
||||
defer cancel()
|
||||
pool := newSessionPool(nil)
|
||||
pool.bond = true
|
||||
server := &bond.Server{}
|
||||
backend := echoBackend(t)
|
||||
for i := range 3 {
|
||||
pool.Add(i+1, pairedBondSession(t, ctx, server, backend), nil)
|
||||
}
|
||||
ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = ln.Close() }()
|
||||
stop := context.AfterFunc(ctx, func() { _ = ln.Close() })
|
||||
defer stop()
|
||||
loopDone := make(chan struct{})
|
||||
go func() { defer close(loopDone); acceptLoop(ctx, &Deps{Log: logx.Nop()}, ln, pool) }()
|
||||
conn := dialBondTest(t, ctx, ln.Addr().String())
|
||||
payload := bytes.Repeat([]byte("bond payload"), 128*1024)
|
||||
checkBondEcho(t, conn, payload)
|
||||
for _, ps := range pool.sessions {
|
||||
if ps.sess.NumStreams() != 1 {
|
||||
t.Fatalf("session %d: expected one bond lane", ps.id)
|
||||
}
|
||||
}
|
||||
_ = pool.sessions[1].sess.Close()
|
||||
if _, err := conn.Read(make([]byte, 1)); err == nil {
|
||||
t.Fatal("broken bond still open")
|
||||
}
|
||||
_ = conn.Close()
|
||||
// Следующее соединение использует оставшиеся сессии без перезапуска listener.
|
||||
conn = dialBondTest(t, ctx, ln.Addr().String())
|
||||
checkBondEcho(t, conn, payload)
|
||||
_ = conn.Close()
|
||||
cancel()
|
||||
select {
|
||||
case <-loopDone:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("accept loop leaked")
|
||||
}
|
||||
}
|
||||
|
||||
func dialBondTest(t *testing.T, ctx context.Context, addr string) net.Conn {
|
||||
t.Helper()
|
||||
conn, err := (&net.Dialer{}).DialContext(ctx, "tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return conn
|
||||
}
|
||||
|
||||
func checkBondEcho(t *testing.T, conn net.Conn, payload []byte) {
|
||||
t.Helper()
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
n, err := conn.Write(payload)
|
||||
if err == nil && n != len(payload) {
|
||||
err = fmt.Errorf("short write %d", n)
|
||||
}
|
||||
done <- err
|
||||
}()
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(conn, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatal("corrupted echo")
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ type pooledSession struct {
|
||||
|
||||
// sessionPool - конкурентно-безопасный round-robin пул живых сессий.
|
||||
type sessionPool struct {
|
||||
bond bool
|
||||
mu sync.RWMutex
|
||||
sessions []*pooledSession
|
||||
counter atomic.Uint64
|
||||
|
||||
@@ -45,6 +45,7 @@ type DialFunc = udprelay.DialFunc
|
||||
type AuthHandler = udprelay.AuthHandler
|
||||
|
||||
type Params struct {
|
||||
Bond bool
|
||||
Dial DialFunc
|
||||
Profile string
|
||||
ObfKey []byte
|
||||
@@ -86,6 +87,7 @@ func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, lis
|
||||
}
|
||||
log := deps.log()
|
||||
pool := newSessionPool(deps.ConnectedStreams)
|
||||
pool.bond = params.Bond
|
||||
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
@@ -98,7 +100,7 @@ func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, lis
|
||||
}
|
||||
stopCloser := context.AfterFunc(runCtx, func() { _ = listener.Close() })
|
||||
defer stopCloser()
|
||||
log.Infof("TCP mode: listening on %s (round-robin across %d sessions)", listenAddr, numSessions)
|
||||
log.Infof("TCP mode: listening on %s (sessions=%d bond=%t)", listenAddr, numSessions, params.Bond)
|
||||
|
||||
fatalCh := make(chan error, 1)
|
||||
fatal := func(err error) {
|
||||
@@ -201,6 +203,12 @@ func acceptLoop(ctx context.Context, deps *Deps, listener net.Listener, pool *se
|
||||
continue
|
||||
}
|
||||
backoff = 0
|
||||
if pool.bond {
|
||||
wg.Go(func() {
|
||||
_ = safego.Run(log, func() { proxyBond(ctx, log, conn, pool) })
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
ps := pool.Pick()
|
||||
if ps == nil {
|
||||
@@ -387,7 +395,11 @@ func createSession(ctx context.Context, deps *Deps, params *Params, peer *net.UD
|
||||
closers = append(closers, func() { _ = dtlsConn.Close() })
|
||||
|
||||
// Wire-контракт: Client ID первой app-record, до KCP.
|
||||
if err = clientsdb.WriteClientID(ctx, dtlsConn, params.ClientID, clientsdb.ModeTCP); err != nil {
|
||||
mode := clientsdb.ModeTCP
|
||||
if params.Bond {
|
||||
mode = clientsdb.ModeTCPBond
|
||||
}
|
||||
if err = clientsdb.WriteClientID(ctx, dtlsConn, params.ClientID, mode); err != nil {
|
||||
cleanup()
|
||||
return nil, fmt.Errorf("send client ID: %w", err)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user