From 09096568ff51fa4843f2b0bc69a52a24c1e6e3d4 Mon Sep 17 00:00:00 2001 From: samosvalishe Date: Tue, 19 May 2026 11:21:48 +0300 Subject: [PATCH] =?UTF-8?q?refactor:=20=D0=B2=D1=8B=D0=BD=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B8=20VLESS-=D1=80=D0=B5=D0=B6=D0=B8=D0=BC=20=D0=B2=20?= =?UTF-8?q?internal/proxy/vless?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Переносит runVLESSMode/maintainVLESSSession/createSmuxSession/pipe и sessionPool в internal/proxy/vless. Клиентская половина bond (handleBondedTCP, copyTCPToBond, copyBondToTCP, bondClientLane) остаётся в client/main.go до этапа 5.1 — инжектится в vless через Deps.BondHandler. sessionPool/pooledSession экспортированы как SessionPool/PooledSession, чтобы половина bond работала со счётчиками lane (ID/Sess/Opened/Active/Closed/ ToSession/FromSession). Также дедуплицирует iSH (linux/386) listener-shim в новый пакет internal/ish; client/manual_captcha.go и internal/proxy/vless импортируют его через ish.WrapListener. client/main.go: 895 → 552 (-343). Wire-формат и CLI не изменены. --- client/ish_listener_other.go | 10 - client/main.go | 415 ++---------------- client/manual_captcha.go | 3 +- .../ish/listener_linux_386.go | 14 +- internal/ish/listener_other.go | 13 + internal/proxy/vless/pool.go | 94 ++++ internal/proxy/vless/vless.go | 333 ++++++++++++++ 7 files changed, 485 insertions(+), 397 deletions(-) delete mode 100644 client/ish_listener_other.go rename client/ish_listener_linux_386.go => internal/ish/listener_linux_386.go (89%) create mode 100644 internal/ish/listener_other.go create mode 100644 internal/proxy/vless/pool.go create mode 100644 internal/proxy/vless/vless.go diff --git a/client/ish_listener_other.go b/client/ish_listener_other.go deleted file mode 100644 index d46659d..0000000 --- a/client/ish_listener_other.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !(linux && 386) - -package main - -import "net" - -// wrapISHListener is a no-op for architectures that don't need the legacy socketcall accept bypass. -func wrapISHListener(ln net.Listener) (net.Listener, error) { - return ln, nil -} diff --git a/client/main.go b/client/main.go index 870d2c6..7871afa 100644 --- a/client/main.go +++ b/client/main.go @@ -25,10 +25,9 @@ import ( "github.com/cacggghp/vk-turn-proxy/internal/bond" "github.com/cacggghp/vk-turn-proxy/internal/dtlsdial" udpproxy "github.com/cacggghp/vk-turn-proxy/internal/proxy/udp" + "github.com/cacggghp/vk-turn-proxy/internal/proxy/vless" "github.com/cacggghp/vk-turn-proxy/internal/stats" - "github.com/cacggghp/vk-turn-proxy/internal/turnpipe" "github.com/cacggghp/vk-turn-proxy/internal/wrap" - "github.com/cacggghp/vk-turn-proxy/tcputil" "github.com/xtaci/smux" ) @@ -192,7 +191,21 @@ func main() { } if *vlessMode { - runVLESSMode(ctx, params, peer, *listen, *n, *vlessBond) + vlessDeps := &vless.Deps{ + DTLSDialer: vlessDtlsDialer, + Debug: isDebug, + Debugf: debugf, + BondHandler: handleBondedTCP, + } + vlessParams := &vless.Params{ + Host: params.host, + Port: params.port, + Link: params.link, + UDP: params.udp, + WrapKey: params.wrapKey, + GetCreds: vless.GetCredsFunc(params.getCreds), + } + vless.Run(ctx, vlessDeps, vlessParams, peer, *listen, *n, *vlessBond) return } @@ -308,84 +321,16 @@ func main() { wg1.Wait() } -// sessionPool manages a pool of smux sessions for round-robin TCP distribution. -type pooledSession struct { - id int - sess *smux.Session - active atomic.Int32 - opened atomic.Uint64 - closed atomic.Uint64 - toSession atomic.Uint64 - fromSession atomic.Uint64 -} - -type sessionPool struct { - mu sync.RWMutex - sessions []*pooledSession - counter atomic.Uint64 - connCounter atomic.Uint64 -} - -func (p *sessionPool) add(id int, s *smux.Session) *pooledSession { - ps := &pooledSession{id: id, sess: s} - p.mu.Lock() - p.sessions = append(p.sessions, ps) - p.mu.Unlock() - return ps -} - -func (p *sessionPool) remove(ps *pooledSession) { - p.mu.Lock() - for i, sess := range p.sessions { - if sess == ps { - p.sessions = append(p.sessions[:i], p.sessions[i+1:]...) - break - } - } - p.mu.Unlock() -} - -func (p *sessionPool) pick() *pooledSession { - p.mu.RLock() - defer p.mu.RUnlock() - n := len(p.sessions) - if n == 0 { - return nil - } - idx := (p.counter.Add(1) - 1) % uint64(n) - return p.sessions[idx] -} - -func (p *sessionPool) nextConnID() uint64 { - return p.connCounter.Add(1) -} - -func (p *sessionPool) snapshot() []*pooledSession { - p.mu.RLock() - defer p.mu.RUnlock() - out := make([]*pooledSession, 0, len(p.sessions)) - for _, ps := range p.sessions { - if !ps.sess.IsClosed() { - out = append(out, ps) - } - } - return out -} - -func (p *sessionPool) count() int { - p.mu.RLock() - defer p.mu.RUnlock() - return len(p.sessions) -} - +// bondClientLane is one striped smux stream within a bonded TCP connection. +// Stays in main during stage 4.2; moves to internal/bond/client in stage 5.1. type bondClientLane struct { - ps *pooledSession + ps *vless.PooledSession stream *smux.Stream mu sync.Mutex dead atomic.Bool } -func handleBondedTCP(ctx context.Context, tcpConn net.Conn, connID uint64, candidates []*pooledSession) { +func handleBondedTCP(ctx context.Context, tcpConn net.Conn, connID uint64, candidates []*vless.PooledSession) { defer func() { _ = tcpConn.Close() }() ctx, cancel := context.WithCancel(ctx) @@ -394,23 +339,23 @@ func handleBondedTCP(ctx context.Context, tcpConn net.Conn, connID uint64, candi lanes := make([]*bondClientLane, 0, len(candidates)) laneIDs := make([]string, 0, len(candidates)) for i, ps := range candidates { - if ps.sess.IsClosed() { + if ps.Sess.IsClosed() { continue } - stream, err := ps.sess.OpenStream() + stream, err := ps.Sess.OpenStream() if err != nil { - log.Printf("[bond %d] session %d open stream error: %s", connID, ps.id, err) + log.Printf("[bond %d] session %d open stream error: %s", connID, ps.ID, err) continue } if err := bond.WriteHello(stream, connID, uint16(i), uint16(len(candidates))); err != nil { - log.Printf("[bond %d] session %d hello error: %s", connID, ps.id, err) + log.Printf("[bond %d] session %d hello error: %s", connID, ps.ID, err) _ = stream.Close() continue } - ps.opened.Add(1) - ps.active.Add(1) + ps.Opened.Add(1) + ps.Active.Add(1) lanes = append(lanes, &bondClientLane{ps: ps, stream: stream}) - laneIDs = append(laneIDs, strconv.Itoa(ps.id)) + laneIDs = append(laneIDs, strconv.Itoa(ps.ID)) } if len(lanes) == 0 { @@ -424,7 +369,7 @@ func handleBondedTCP(ctx context.Context, tcpConn net.Conn, connID uint64, candi } for _, lane := range lanes { if err := lane.stream.SetDeadline(now); err != nil && isDebug { - log.Printf("[bond %d] session %d stream deadline error: %v", connID, lane.ps.id, err) + log.Printf("[bond %d] session %d stream deadline error: %v", connID, lane.ps.ID, err) } } }) @@ -433,11 +378,11 @@ func handleBondedTCP(ctx context.Context, tcpConn net.Conn, connID uint64, candi defer func() { for _, lane := range lanes { _ = lane.stream.Close() - active := lane.ps.active.Add(-1) - closed := lane.ps.closed.Add(1) + active := lane.ps.Active.Add(-1) + closed := lane.ps.Closed.Add(1) debugf("[bond %d] lane session %d close active=%d closed=%d totals: to-session=%s from-session=%s", - connID, lane.ps.id, active, closed, - stats.FormatByteCount(lane.ps.toSession.Load()), stats.FormatByteCount(lane.ps.fromSession.Load())) + connID, lane.ps.ID, active, closed, + stats.FormatByteCount(lane.ps.ToSession.Load()), stats.FormatByteCount(lane.ps.FromSession.Load())) } }() @@ -454,13 +399,13 @@ func handleBondedTCP(ctx context.Context, tcpConn net.Conn, connID uint64, candi case <-ctx.Done(): default: if err != io.EOF { - debugf("[bond %d] session %d read frame error: %v", connID, l.ps.id, err) + debugf("[bond %d] session %d read frame error: %v", connID, l.ps.ID, err) } } return } if f.Type == bond.FrameData { - l.ps.fromSession.Add(uint64(len(f.Data))) + l.ps.FromSession.Add(uint64(len(f.Data))) } select { case recvCh <- f: @@ -498,7 +443,7 @@ func copyTCPToBond(ctx context.Context, connID uint64, tcpConn net.Conn, lanes [ log.Printf("[bond %d] write data error: %v", connID, writeErr) return } - lane.ps.toSession.Add(uint64(n)) + lane.ps.ToSession.Add(uint64(n)) seq++ } if err != nil { @@ -513,7 +458,7 @@ func copyTCPToBond(ctx context.Context, connID uint64, tcpConn net.Conn, lanes [ writeErr := bond.WriteFrame(lane.stream, bond.FrameFIN, seq, nil) lane.mu.Unlock() if writeErr != nil && ctx.Err() == nil { - log.Printf("[bond %d] session %d write FIN error: %v", connID, lane.ps.id, writeErr) + log.Printf("[bond %d] session %d write FIN error: %v", connID, lane.ps.ID, writeErr) } } debugf("[bond %d] upload finished chunks=%d", connID, seq) @@ -605,291 +550,3 @@ func copyBondToTCP(ctx context.Context, connID uint64, tcpConn net.Conn, recvCh } } } - -// runVLESSMode implements TCP forwarding with round-robin across N TURN sessions. -func runVLESSMode(ctx context.Context, tp *turnParams, peer *net.UDPAddr, listenAddr string, numSessions int, useBond bool) { - pool := &sessionPool{} - - // Start N session maintainers with staggered startup - var wgMaint sync.WaitGroup - for id := range numSessions { - wgMaint.Go(func() { - select { - case <-ctx.Done(): - return - case <-time.After(time.Duration(id) * 300 * time.Millisecond): - } - maintainVLESSSession(ctx, tp, peer, id, pool) - }) - } - - // Wait for at least one session - log.Printf("VLESS mode: waiting for sessions to connect (total: %d)...", numSessions) - for { - select { - case <-ctx.Done(): - wgMaint.Wait() - return - case <-time.After(100 * time.Millisecond): - } - if pool.count() > 0 { - break - } - } - - listener, err := net.Listen("tcp", listenAddr) - if err != nil { - log.Panicf("TCP listen: %s", err) - } - - wrappedListener, err := wrapISHListener(listener) - if err != nil { - log.Printf("Warning: failed to wrap listener: %v", err) - wrappedListener = listener - } - - context.AfterFunc(ctx, func() { _ = wrappedListener.Close() }) - if useBond { - log.Printf("VLESS bond mode: listening on %s (striping each TCP connection across active sessions)", listenAddr) - } else { - log.Printf("VLESS mode: listening on %s (round-robin across %d sessions)", listenAddr, numSessions) - } - - var wgConn sync.WaitGroup - for { - tcpConn, err := wrappedListener.Accept() - if err != nil { - select { - case <-ctx.Done(): - wgConn.Wait() - wgMaint.Wait() - return - default: - } - log.Printf("TCP accept error: %s", err) - continue - } - - if useBond { - connID := (uint64(time.Now().UnixNano()) << 16) ^ pool.nextConnID() - lanes := pool.snapshot() - if len(lanes) == 0 { - log.Printf("No active sessions, rejecting connection") - _ = tcpConn.Close() - continue - } - - tc, cid, lns := tcpConn, connID, lanes - wgConn.Go(func() { - handleBondedTCP(ctx, tc, cid, lns) - }) - continue - } - - ps := pool.pick() - if ps == nil || ps.sess.IsClosed() { - log.Printf("No active sessions, rejecting connection") - _ = tcpConn.Close() - continue - } - - connID := pool.nextConnID() - opened := ps.opened.Add(1) - active := ps.active.Add(1) - debugf("[session %d] TCP accept #%d from=%s active=%d opened=%d pool=%d", - ps.id, connID, tcpConn.RemoteAddr(), active, opened, pool.count()) - - tc, sessRef, cid := tcpConn, ps, connID - wgConn.Go(func() { - defer func() { _ = tc.Close() }() - defer func() { - active := sessRef.active.Add(-1) - closed := sessRef.closed.Add(1) - debugf("[session %d] TCP close #%d active=%d closed=%d totals: to-session=%s from-session=%s", - sessRef.id, cid, active, closed, - stats.FormatByteCount(sessRef.toSession.Load()), stats.FormatByteCount(sessRef.fromSession.Load())) - }() - - stream, err := sessRef.sess.OpenStream() - if err != nil { - log.Printf("[session %d] smux open stream error for TCP #%d: %s", sessRef.id, cid, err) - return - } - defer func() { _ = stream.Close() }() - fromSession, toSession := pipe(ctx, tc, stream) - sessRef.fromSession.Add(uint64(fromSession)) - sessRef.toSession.Add(uint64(toSession)) - debugf("[session %d] TCP done #%d local<-session=%s local->session=%s", - sessRef.id, cid, stats.FormatByteCount(uint64(fromSession)), stats.FormatByteCount(uint64(toSession))) - }) - } -} - -// maintainVLESSSession keeps one TURN+DTLS+KCP+smux session alive, reconnecting on failure. -func maintainVLESSSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr, id int, pool *sessionPool) { - for { - select { - case <-ctx.Done(): - return - default: - } - - smuxSess, cleanup, err := createSmuxSession(ctx, tp, peer, id) - if err != nil { - log.Printf("[session %d] setup error: %s, retrying...", id, err) - select { - case <-ctx.Done(): - return - case <-time.After(3 * time.Second): - } - continue - } - - ps := pool.add(id, smuxSess) - log.Printf("[session %d] connected (active: %d)", id, pool.count()) - - for !smuxSess.IsClosed() { - select { - case <-ctx.Done(): - pool.remove(ps) - cleanup() - return - case <-time.After(1 * time.Second): - } - } - - pool.remove(ps) - cleanup() - log.Printf("[session %d] disconnected (active: %d), reconnecting...", id, pool.count()) - - select { - case <-ctx.Done(): - return - case <-time.After(2 * time.Second): - } - } -} - -// createSmuxSession establishes a full TURN+DTLS+KCP+smux pipeline and returns -// the smux session along with a cleanup function to tear down all layers. -func createSmuxSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr, id int) (*smux.Session, func(), error) { - var cleanupFns []func() - cleanup := func() { - for i := len(cleanupFns) - 1; i >= 0; i-- { - cleanupFns[i]() - } - } - - // 1. Get TURN credentials - user, pass, rawURL, err := tp.getCreds(ctx, tp.link, id) - if err != nil { - return nil, nil, fmt.Errorf("get TURN creds: %w", err) - } - - // 2-3. Dial TURN and allocate relay. - stream, err := turnpipe.Open(ctx, turnpipe.Config{ - HostOverride: tp.host, - PortOverride: tp.port, - UDP: tp.udp, - }, peer, user, pass, rawURL) - if err != nil { - return nil, nil, err - } - cleanupFns = append(cleanupFns, func() { _ = stream.Close() }) - relayConn := stream.Relay - debugf("[session %d] TURN server IP: %s", id, stream.ServerUDPAddr.IP) - debugf("relayed-address=%s", relayConn.LocalAddr().String()) - - // 4. Establish DTLS over TURN relay - var relayWC *wrap.Conn - if len(tp.wrapKey) == wrap.KeyLen { - relayWC, err = wrap.NewConn(tp.wrapKey, false) - if err != nil { - cleanup() - return nil, nil, fmt.Errorf("wrap init: %w", err) - } - } - dtlsPC := &wrap.RelayPacketConn{Relay: relayConn, Peer: peer, Conn: relayWC} - dtlsConn, err := vlessDtlsDialer.Dial(ctx, dtlsPC, peer) - if err != nil { - cleanup() - return nil, nil, fmt.Errorf("DTLS handshake: %w", err) - } - cleanupFns = append(cleanupFns, func() { _ = dtlsConn.Close() }) - debugf("DTLS connection established") - - // 5. Create KCP session over DTLS - statsCtx, statsCancel := context.WithCancel(ctx) - cleanupFns = append(cleanupFns, statsCancel) - st := stats.New(isDebug) - go st.LogEvery(statsCtx, debugf, fmt.Sprintf("[session %d] VLESS", id), "to-turn", "from-turn") - - kcpSess, err := tcputil.NewKCPOverDTLS(&stats.CountingConn{Conn: dtlsConn, Stats: st}, false) - if err != nil { - cleanup() - return nil, nil, fmt.Errorf("KCP session: %w", err) - } - cleanupFns = append(cleanupFns, func() { _ = kcpSess.Close() }) - debugf("KCP session established") - - // 6. Create smux client session over KCP - smuxSess, err := smux.Client(kcpSess, tcputil.DefaultSmuxConfig()) - if err != nil { - cleanup() - return nil, nil, fmt.Errorf("smux client: %w", err) - } - cleanupFns = append(cleanupFns, func() { _ = smuxSess.Close() }) - debugf("smux session established") - - return smuxSess, cleanup, nil -} - -// pipe copies data bidirectionally between two connections. -// It returns bytes copied as c1<-c2 and c2<-c1. -func pipe(ctx context.Context, c1, c2 net.Conn) (int64, int64) { - ctx2, cancel := context.WithCancel(ctx) - context.AfterFunc(ctx2, func() { - if err := c1.SetDeadline(time.Now()); err != nil { - log.Printf("pipe: failed to set deadline c1: %v", err) - } - if err := c2.SetDeadline(time.Now()); err != nil { - log.Printf("pipe: failed to set deadline c2: %v", err) - } - }) - - var wg sync.WaitGroup - var c1FromC2 int64 - var c2FromC1 int64 - wg.Go(func() { - defer cancel() - n, err := io.Copy(c1, c2) - c1FromC2 = n - if err != nil { - if isDebug { - log.Printf("pipe: c1<-c2 copy error: %v", err) - } - } - }) - wg.Go(func() { - defer cancel() - n, err := io.Copy(c2, c1) - c2FromC1 = n - if err != nil { - if isDebug { - log.Printf("pipe: c2<-c1 copy error: %v", err) - } - } - }) - wg.Wait() - if err := c1.SetDeadline(time.Time{}); err != nil { - if isDebug { - log.Printf("pipe: failed to reset deadline c1: %v", err) - } - } - if err := c2.SetDeadline(time.Time{}); err != nil { - if isDebug { - log.Printf("pipe: failed to reset deadline c2: %v", err) - } - } - return c1FromC2, c2FromC1 -} diff --git a/client/manual_captcha.go b/client/manual_captcha.go index 47807ed..6bf1bd5 100644 --- a/client/manual_captcha.go +++ b/client/manual_captcha.go @@ -20,6 +20,7 @@ import ( "time" "github.com/cacggghp/vk-turn-proxy/client/internal/browserprofile" + "github.com/cacggghp/vk-turn-proxy/internal/ish" ) const captchaListenPort = "8765" @@ -503,7 +504,7 @@ func startCaptchaServer(srv *http.Server, logPrefix string) error { continue } listening = true - wrappedListener, err := wrapISHListener(listener) + wrappedListener, err := ish.WrapListener(listener) if err != nil { log.Printf("%s: failed to wrap listener for iSH: %v", logPrefix, err) wrappedListener = listener diff --git a/client/ish_listener_linux_386.go b/internal/ish/listener_linux_386.go similarity index 89% rename from client/ish_listener_linux_386.go rename to internal/ish/listener_linux_386.go index 25ab1e2..79274c7 100644 --- a/client/ish_listener_linux_386.go +++ b/internal/ish/listener_linux_386.go @@ -1,6 +1,6 @@ //go:build linux && 386 -package main +package ish import ( "io" @@ -11,15 +11,15 @@ import ( "unsafe" ) -type ishListener struct { +type listener struct { net.Listener f *os.File fd int } -// wrapISHListener overrides the standard net.Listener with a legacy syscall listener +// WrapListener overrides the standard net.Listener with a legacy syscall listener // designed specifically for the iSH simulator on iOS, which lacks modern `accept4`. -func wrapISHListener(ln net.Listener) (net.Listener, error) { +func WrapListener(ln net.Listener) (net.Listener, error) { tl, ok := ln.(*net.TCPListener) if !ok { return ln, nil @@ -30,10 +30,10 @@ func wrapISHListener(ln net.Listener) (net.Listener, error) { } // Keep a reference to *os.File so the garbage collector doesn't close the FD. - return &ishListener{Listener: ln, f: f, fd: int(f.Fd())}, nil + return &listener{Listener: ln, f: f, fd: int(f.Fd())}, nil } -func (l *ishListener) Accept() (net.Conn, error) { +func (l *listener) Accept() (net.Conn, error) { // Set the listener socket to blocking mode. Go makes it non-blocking by default. // This avoids using time.Sleep in a spin-loop, which triggers futex_time64 SIGSYS in modern Go on iSH. if err := syscall.SetNonblock(l.fd, false); err != nil { @@ -70,7 +70,7 @@ func (l *ishListener) Accept() (net.Conn, error) { } } -func (l *ishListener) Close() error { +func (l *listener) Close() error { // Close both the duplicated FD and the original listener. err1 := l.f.Close() err2 := l.Listener.Close() diff --git a/internal/ish/listener_other.go b/internal/ish/listener_other.go new file mode 100644 index 0000000..d551b33 --- /dev/null +++ b/internal/ish/listener_other.go @@ -0,0 +1,13 @@ +//go:build !(linux && 386) + +// Package ish provides a TCP listener shim for the iSH iOS simulator on +// linux/386, which lacks modern accept4 and Go's epoll-based poller. On every +// other GOOS/GOARCH WrapListener is a no-op pass-through. +package ish + +import "net" + +// WrapListener returns ln unchanged on non-iSH platforms. +func WrapListener(ln net.Listener) (net.Listener, error) { + return ln, nil +} diff --git a/internal/proxy/vless/pool.go b/internal/proxy/vless/pool.go new file mode 100644 index 0000000..d657c7f --- /dev/null +++ b/internal/proxy/vless/pool.go @@ -0,0 +1,94 @@ +// Package vless implements VLESS mode: TCP forwarding over a pool of TURN-tunneled +// smux sessions. Each accepted local TCP connection is opened as a smux stream +// (round-robin across sessions) or, with bond, striped across all live sessions. +// +// The package exposes SessionPool/PooledSession so that the bond client half +// (still living in main during refactor stage 4.2) can operate on them. +package vless + +import ( + "sync" + "sync/atomic" + + "github.com/xtaci/smux" +) + +// PooledSession is a single TURN+DTLS+KCP+smux session inside the pool, with +// its lifetime counters. Fields are exported so the bond client (in main) can +// account per-lane traffic; mutate via the atomic operations only. +type PooledSession struct { + ID int + Sess *smux.Session + Active atomic.Int32 + Opened atomic.Uint64 + Closed atomic.Uint64 + ToSession atomic.Uint64 + FromSession atomic.Uint64 +} + +// SessionPool is a concurrency-safe round-robin pool of live smux sessions. +type SessionPool struct { + mu sync.RWMutex + sessions []*PooledSession + counter atomic.Uint64 + connCounter atomic.Uint64 +} + +// Add registers a freshly connected session in the pool. +func (p *SessionPool) Add(id int, s *smux.Session) *PooledSession { + ps := &PooledSession{ID: id, Sess: s} + p.mu.Lock() + p.sessions = append(p.sessions, ps) + p.mu.Unlock() + return ps +} + +// Remove drops ps from the pool. No-op if not present. +func (p *SessionPool) Remove(ps *PooledSession) { + p.mu.Lock() + for i, sess := range p.sessions { + if sess == ps { + p.sessions = append(p.sessions[:i], p.sessions[i+1:]...) + break + } + } + p.mu.Unlock() +} + +// Pick returns the next session in round-robin order, or nil if pool is empty. +func (p *SessionPool) Pick() *PooledSession { + p.mu.RLock() + defer p.mu.RUnlock() + n := len(p.sessions) + if n == 0 { + return nil + } + idx := (p.counter.Add(1) - 1) % uint64(n) + return p.sessions[idx] +} + +// NextConnID returns a monotonically increasing connection ID. +func (p *SessionPool) NextConnID() uint64 { + return p.connCounter.Add(1) +} + +// Snapshot returns a copy of all currently-live (non-closed) sessions. +func (p *SessionPool) Snapshot() []*PooledSession { + p.mu.RLock() + defer p.mu.RUnlock() + out := make([]*PooledSession, 0, len(p.sessions)) + for _, ps := range p.sessions { + if !ps.Sess.IsClosed() { + out = append(out, ps) + } + } + return out +} + +// Count returns the number of sessions currently in the pool (including any +// that may have just closed; use Snapshot for live-only). +func (p *SessionPool) Count() int { + p.mu.RLock() + defer p.mu.RUnlock() + return len(p.sessions) +} diff --git a/internal/proxy/vless/vless.go b/internal/proxy/vless/vless.go new file mode 100644 index 0000000..22f5e4f --- /dev/null +++ b/internal/proxy/vless/vless.go @@ -0,0 +1,333 @@ +package vless + +import ( + "context" + "fmt" + "io" + "log" + "net" + "sync" + "time" + + "github.com/cacggghp/vk-turn-proxy/internal/dtlsdial" + "github.com/cacggghp/vk-turn-proxy/internal/ish" + "github.com/cacggghp/vk-turn-proxy/internal/stats" + "github.com/cacggghp/vk-turn-proxy/internal/turnpipe" + "github.com/cacggghp/vk-turn-proxy/internal/wrap" + "github.com/cacggghp/vk-turn-proxy/tcputil" + "github.com/xtaci/smux" +) + +// GetCredsFunc resolves VK TURN credentials for a (link, streamID) pair. +type GetCredsFunc func(ctx context.Context, link string, streamID int) (string, string, string, error) + +// Params is the per-pool TURN/wrap configuration. +type Params struct { + Host string + Port string + Link string + UDP bool + WrapKey []byte + GetCreds GetCredsFunc +} + +// BondHandler stripes one accepted TCP connection across all currently-live +// pool sessions. Nil disables bond mode (callers will then use round-robin). +// Bond client lives in main during stage 4.2; it will move to internal/bond/client +// in stage 5.1. +type BondHandler func(ctx context.Context, tcpConn net.Conn, connID uint64, lanes []*PooledSession) + +// Deps groups host-process dependencies needed by the VLESS loop. +type Deps struct { + DTLSDialer *dtlsdial.Dialer + Debug bool + Debugf func(format string, v ...any) + BondHandler BondHandler +} + +func (d *Deps) debugf(format string, v ...any) { + if d.Debugf != nil { + d.Debugf(format, v...) + } +} + +// Run is the VLESS-mode entrypoint. It spawns numSessions maintainers, waits +// for at least one to connect, then accepts local TCP connections and forwards +// each as a smux stream (round-robin) or bonded across all live sessions. +func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, listenAddr string, numSessions int, useBond bool) { + pool := &SessionPool{} + + var wgMaint sync.WaitGroup + for id := range numSessions { + wgMaint.Go(func() { + select { + case <-ctx.Done(): + return + case <-time.After(time.Duration(id) * 300 * time.Millisecond): + } + maintainSession(ctx, deps, params, peer, id, pool) + }) + } + + log.Printf("VLESS mode: waiting for sessions to connect (total: %d)...", numSessions) + for { + select { + case <-ctx.Done(): + wgMaint.Wait() + return + case <-time.After(100 * time.Millisecond): + } + if pool.Count() > 0 { + break + } + } + + listener, err := net.Listen("tcp", listenAddr) + if err != nil { + log.Panicf("TCP listen: %s", err) + } + + wrappedListener, err := ish.WrapListener(listener) + if err != nil { + log.Printf("Warning: failed to wrap listener: %v", err) + wrappedListener = listener + } + + context.AfterFunc(ctx, func() { _ = wrappedListener.Close() }) + if useBond { + log.Printf("VLESS bond mode: listening on %s (striping each TCP connection across active sessions)", listenAddr) + } else { + log.Printf("VLESS mode: listening on %s (round-robin across %d sessions)", listenAddr, numSessions) + } + + var wgConn sync.WaitGroup + for { + tcpConn, err := wrappedListener.Accept() + if err != nil { + select { + case <-ctx.Done(): + wgConn.Wait() + wgMaint.Wait() + return + default: + } + log.Printf("TCP accept error: %s", err) + continue + } + + if useBond { + if deps.BondHandler == nil { + log.Printf("bond requested but no BondHandler set, rejecting") + _ = tcpConn.Close() + continue + } + connID := (uint64(time.Now().UnixNano()) << 16) ^ pool.NextConnID() + lanes := pool.Snapshot() + if len(lanes) == 0 { + log.Printf("No active sessions, rejecting connection") + _ = tcpConn.Close() + continue + } + + tc, cid, lns := tcpConn, connID, lanes + wgConn.Go(func() { + deps.BondHandler(ctx, tc, cid, lns) + }) + continue + } + + ps := pool.Pick() + if ps == nil || ps.Sess.IsClosed() { + log.Printf("No active sessions, rejecting connection") + _ = tcpConn.Close() + continue + } + + connID := pool.NextConnID() + opened := ps.Opened.Add(1) + active := ps.Active.Add(1) + deps.debugf("[session %d] TCP accept #%d from=%s active=%d opened=%d pool=%d", + ps.ID, connID, tcpConn.RemoteAddr(), active, opened, pool.Count()) + + tc, sessRef, cid := tcpConn, ps, connID + wgConn.Go(func() { + defer func() { _ = tc.Close() }() + defer func() { + active := sessRef.Active.Add(-1) + closed := sessRef.Closed.Add(1) + deps.debugf("[session %d] TCP close #%d active=%d closed=%d totals: to-session=%s from-session=%s", + sessRef.ID, cid, active, closed, + stats.FormatByteCount(sessRef.ToSession.Load()), stats.FormatByteCount(sessRef.FromSession.Load())) + }() + + stream, err := sessRef.Sess.OpenStream() + if err != nil { + log.Printf("[session %d] smux open stream error for TCP #%d: %s", sessRef.ID, cid, err) + return + } + defer func() { _ = stream.Close() }() + fromSession, toSession := pipe(deps, ctx, tc, stream) + sessRef.FromSession.Add(uint64(fromSession)) + sessRef.ToSession.Add(uint64(toSession)) + deps.debugf("[session %d] TCP done #%d local<-session=%s local->session=%s", + sessRef.ID, cid, stats.FormatByteCount(uint64(fromSession)), stats.FormatByteCount(uint64(toSession))) + }) + } +} + +// maintainSession keeps one TURN+DTLS+KCP+smux session alive, reconnecting on +// failure with a fixed 2-3s backoff. +func maintainSession(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, id int, pool *SessionPool) { + for { + select { + case <-ctx.Done(): + return + default: + } + + smuxSess, cleanup, err := createSmuxSession(ctx, deps, params, peer, id) + if err != nil { + log.Printf("[session %d] setup error: %s, retrying...", id, err) + select { + case <-ctx.Done(): + return + case <-time.After(3 * time.Second): + } + continue + } + + ps := pool.Add(id, smuxSess) + log.Printf("[session %d] connected (active: %d)", id, pool.Count()) + + for !smuxSess.IsClosed() { + select { + case <-ctx.Done(): + pool.Remove(ps) + cleanup() + return + case <-time.After(1 * time.Second): + } + } + + pool.Remove(ps) + cleanup() + log.Printf("[session %d] disconnected (active: %d), reconnecting...", id, pool.Count()) + + select { + case <-ctx.Done(): + return + case <-time.After(2 * time.Second): + } + } +} + +// createSmuxSession establishes a full TURN+DTLS+KCP+smux pipeline and returns +// the smux session along with a cleanup function (LIFO teardown). +func createSmuxSession(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, id int) (*smux.Session, func(), error) { + var cleanupFns []func() + cleanup := func() { + for i := len(cleanupFns) - 1; i >= 0; i-- { + cleanupFns[i]() + } + } + + user, pass, rawURL, err := params.GetCreds(ctx, params.Link, id) + if err != nil { + return nil, nil, fmt.Errorf("get TURN creds: %w", err) + } + + stream, err := turnpipe.Open(ctx, turnpipe.Config{ + HostOverride: params.Host, + PortOverride: params.Port, + UDP: params.UDP, + }, peer, user, pass, rawURL) + if err != nil { + return nil, nil, err + } + cleanupFns = append(cleanupFns, func() { _ = stream.Close() }) + relayConn := stream.Relay + deps.debugf("[session %d] TURN server IP: %s", id, stream.ServerUDPAddr.IP) + deps.debugf("relayed-address=%s", relayConn.LocalAddr().String()) + + var relayWC *wrap.Conn + if len(params.WrapKey) == wrap.KeyLen { + relayWC, err = wrap.NewConn(params.WrapKey, false) + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("wrap init: %w", err) + } + } + dtlsPC := &wrap.RelayPacketConn{Relay: relayConn, Peer: peer, Conn: relayWC} + dtlsConn, err := deps.DTLSDialer.Dial(ctx, dtlsPC, peer) + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("DTLS handshake: %w", err) + } + cleanupFns = append(cleanupFns, func() { _ = dtlsConn.Close() }) + deps.debugf("DTLS connection established") + + statsCtx, statsCancel := context.WithCancel(ctx) + cleanupFns = append(cleanupFns, statsCancel) + st := stats.New(deps.Debug) + go st.LogEvery(statsCtx, deps.debugf, fmt.Sprintf("[session %d] VLESS", id), "to-turn", "from-turn") + + kcpSess, err := tcputil.NewKCPOverDTLS(&stats.CountingConn{Conn: dtlsConn, Stats: st}, false) + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("KCP session: %w", err) + } + cleanupFns = append(cleanupFns, func() { _ = kcpSess.Close() }) + deps.debugf("KCP session established") + + smuxSess, err := smux.Client(kcpSess, tcputil.DefaultSmuxConfig()) + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("smux client: %w", err) + } + cleanupFns = append(cleanupFns, func() { _ = smuxSess.Close() }) + deps.debugf("smux session established") + + return smuxSess, cleanup, nil +} + +// pipe copies data bidirectionally between two connections, cancelling both +// sides as soon as either copy finishes. Returns (c1<-c2, c2<-c1) bytes. +func pipe(deps *Deps, ctx context.Context, c1, c2 net.Conn) (int64, int64) { + ctx2, cancel := context.WithCancel(ctx) + context.AfterFunc(ctx2, func() { + if err := c1.SetDeadline(time.Now()); err != nil { + log.Printf("pipe: failed to set deadline c1: %v", err) + } + if err := c2.SetDeadline(time.Now()); err != nil { + log.Printf("pipe: failed to set deadline c2: %v", err) + } + }) + + var wg sync.WaitGroup + var c1FromC2 int64 + var c2FromC1 int64 + wg.Go(func() { + defer cancel() + n, err := io.Copy(c1, c2) + c1FromC2 = n + if err != nil && deps.Debug { + log.Printf("pipe: c1<-c2 copy error: %v", err) + } + }) + wg.Go(func() { + defer cancel() + n, err := io.Copy(c2, c1) + c2FromC1 = n + if err != nil && deps.Debug { + log.Printf("pipe: c2<-c1 copy error: %v", err) + } + }) + wg.Wait() + if err := c1.SetDeadline(time.Time{}); err != nil && deps.Debug { + log.Printf("pipe: failed to reset deadline c1: %v", err) + } + if err := c2.SetDeadline(time.Time{}); err != nil && deps.Debug { + log.Printf("pipe: failed to reset deadline c2: %v", err) + } + return c1FromC2, c2FromC1 +}