diff --git a/internal/proxy/tcpfwd/pool.go b/internal/proxy/tcpfwd/pool.go index 1c83c5e..4cbbcfd 100644 --- a/internal/proxy/tcpfwd/pool.go +++ b/internal/proxy/tcpfwd/pool.go @@ -32,6 +32,20 @@ type SessionPool struct { sessions []*PooledSession counter atomic.Uint64 connCounter atomic.Uint64 + + readyOnce sync.Once + ready chan struct{} +} + +// Ready returns a channel closed the first time the pool gains a session. +func (p *SessionPool) Ready() <-chan struct{} { + p.mu.Lock() + if p.ready == nil { + p.ready = make(chan struct{}) + } + ch := p.ready + p.mu.Unlock() + return ch } // Add registers a freshly connected session in the pool. @@ -39,7 +53,12 @@ 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) + if p.ready == nil { + p.ready = make(chan struct{}) + } + ready := p.ready p.mu.Unlock() + p.readyOnce.Do(func() { close(ready) }) return ps } diff --git a/internal/proxy/tcpfwd/tcpfwd.go b/internal/proxy/tcpfwd/tcpfwd.go index 9a05a43..400234b 100644 --- a/internal/proxy/tcpfwd/tcpfwd.go +++ b/internal/proxy/tcpfwd/tcpfwd.go @@ -70,16 +70,11 @@ func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, lis } deps.log().Infof("VLESS mode: waiting for sessions to connect (total: %d)...", numSessions) - for { - select { - case <-ctx.Done(): - wgMaint.Wait() - return nil - case <-time.After(100 * time.Millisecond): - } - if pool.Count() > 0 { - break - } + select { + case <-ctx.Done(): + wgMaint.Wait() + return nil + case <-pool.Ready(): } listener, err := net.Listen("tcp", listenAddr) @@ -105,12 +100,10 @@ func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, lis for { tcpConn, err := wrappedListener.Accept() if err != nil { - select { - case <-ctx.Done(): + if ctx.Err() != nil { wgConn.Wait() wgMaint.Wait() return nil - default: } deps.log().Errorf("TCP accept error: %s", err) continue